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;
}

相关文章