如何使纯虚函数成为 operator+();功能。 我在基础课上喜欢这个吗 int 运算符+()=0; 编译器给出错误。 在派生类 operator+() 函数中 编译器说派生类不能使 .因为下面的类是抽象的 我知道我不能创建抽象类的对象,但现在我尝试创建派生类对象。
这是代码
#include <iostream>
using namespace std;
class ana {
protected :
int x;
public :
virtual int operator+()=0;
virtual void operator=(ana&)=0;
};
class baba : public ana{
public:
baba(int k){x=k;}
int operator+(baba &ali){
int k;
k=x+ali.x;
return k;
}
void operator=(baba &ali){
x=ali.x;
}
};
int main(){
baba k(4);
return 0;
}
最佳答案
您对代码的模糊提及基本上无法理解。回答你的问题“我怎样才能使纯虚函数成为 operator+(); 函数”,这绝对没有 secret ,例如考虑以下简单程序:
#include <iostream>
class base {
public:
virtual int operator+(int) const = 0;
};
class deriv: public base {
public:
int operator+(int) const {return 23;}
};
int main() {
deriv d;
base& b = d;
std::cout << b + 15 << std::endl;
return 0;
}
这可以正常编译和运行,并按预期发出 23
。无论您做错了什么,显然它必须与此不同(并且可能与运算符重载为纯虚拟的特定问题无关)。
编辑:(根据评论,将 const
添加到方法中,以防万一您想使用 const base&
调用它 - - 请注意,其他答案也省略了这个 const
; 并且,也根据评论):
如果您还想能够执行 15 + b
,只需为此目的添加一个独立函数,比如在 main
之前:
inline int operator+(int i, const base&b) {
return b + i;
}
关于c++运算符重载的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2969966/