c++ polymorphism of operator overloading(c++ 运算符重载的多态性)
问题描述
如何使纯虚函数成为 operator+();功能.我在基类中这样做整数运算符+()=0;编译器给出错误.在派生类 operator+() 函数中编译器说派生类不能 make .因为下面的类是抽象的我知道我不能创建抽象类的对象,但现在我尝试创建派生类对象.
How can I make pure virtual function a operator+(); function. wheh ı do like this in base class int operator+()=0; compiler gives error . in derive class operator+() function compiler say that derive class cannot make . because following class is abstract I know that I cannot create object of abstract classes but now I try to make derive class object.
这里是代码
#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+(); 函数",这绝对没有什么秘密,例如考虑以下简单的程序:
Your vague mentions of code are essentially impossible to follow. Answering your question "How can I make pure virtual function a operator+(); function", there's absolutely no secret to it, e.g. consider the following trivial program:
#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
.无论您做错了什么,显然它必须与此不同(并且可能与将运算符重载为纯虚拟的特定问题无关).
This compiles and runs just fine and emits 23
as expected. Whatever it is that you're doing wrong, obviously it must therefore be different from this (and probably not connected to the specific issue of having an operator overload be pure virtual).
编辑:(根据评论,将 const
添加到方法中,以防万一您想使用 const base&
调用它-- 请注意,其他答案也省略了这个 const
;并且,也根据评论):
Edit: (as per comments, added const
to the method just in case you want to call it w/a const base&
-- note that other answers have also omitted this const
; and, also per comments):
如果你还想实现 15 + b
,只需为此目的添加一个独立函数,例如在 main
之前:
If you want to be able to also do 15 + b
, just add a free-standing function for that very purpose, say just before main
:
inline int operator+(int i, const base&b) {
return b + i;
}
这篇关于c++ 运算符重载的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ 运算符重载的多态性
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01