0
我正在学习C++,我试图做一些多态性和运算符重载,我有一些问题。抽象类重载算术运算符
我在做什么这里是被叫号码,并呼吁敏,我需要重载运算符+,一类衍生化的抽象基类 - 为了与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;
}
当我把2个参数抛出下一个错误'数字* MyInt ::运算符+(数字*,数字*)'必须采取零或一个参数 数字*运算符+(数字* n,数字*米) – Frank
对不起对于丑陋的代码,我是新来的C++,我会看看有关dynamic_cast的信息。感谢您的答复 – Frank