【发布时间】:2016-07-15 22:33:38
【问题描述】:
我正在学习 c++,我正在尝试做一些多态性和运算符重载,但我遇到了一些问题。
我在这里做的是一个名为 Number 的抽象基类和一个名为 MyInt 的派生类,我需要重载 operator+,- 以便使用 MyInt 数字、MyDouble 数字...等进行操作
在阅读了许多帖子后,我陷入了这个错误error: invalid operands of types 'Number*' and 'Number*' to binary 'operator+' cout << n + m << endl;我怎样才能做到这一点?
我知道这可以使用模板,但我不能在这里使用它,因为这个练习的重点是创建类似 MyStack<Number*> 的东西来保存不同的数据类型
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Number {
public:
virtual Number* operator+(Number* n) = 0;
virtual string toString() = 0;
friend ostream& operator<<(ostream& os, Number* n){
return os << n->toString();
}
};
class MyInt: public Number{
public:
int value;
MyInt(int e){
value = e;
}
virtual ~MyInt(){}
int getNum(){ return value;}
Number* operator+(Number* n){
MyInt* a = (MyInt*) n;
return new MyInt(value + a->value);
}
string toString(){
ostringstream oss;
oss << value;
return oss.str();
}
};
int main(int argc, char** argv) {
Number* n = new MyInt(5);
Number* m = new MyInt(3);
cout << "N: " << n << endl;
cout << "M: " << m << endl;
cout << n + m << endl;
return 0;
}
【问题讨论】:
标签: c++ pointers abstract-class pure-virtual