c ++运算符重载的多态性 [英] c++ polymorphism of operator overloading

查看:31
本文介绍了c ++运算符重载的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使纯虚函数成为 operator+();功能.我在基类中喜欢这个int 运算符+()=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 ++运算符重载的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆