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

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

问题描述

如何使纯虚函数成为operator +();功能. 我在基础课上喜欢这样 int运算符+()= 0; 编译器给出错误信息. 在派生类operator +()函数中 编译器说派生类无法制造.因为跟随类是抽象的 我知道我无法创建抽象类的对象,但是现在我尝试使派生类对象成为对象.

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&调用它-请注意,其他答案也省略了此;以及每条评论):

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天全站免登陆