兽i 2022-08-31 20:37 采纳率: 0%
浏览 14

如何在子类中重写父类的重载运算符+函数?

问题遇到的现象和发生背景

如何在子类中重写父类的重载运算符+函数?
其中父类是个抽象类,它的重载运算符+函数是个纯虚函数。

问题相关代码,请勿粘贴截图

class Father
{
public:
virtual Father* operator+(Father*) = 0;
};

class Son:public Father
{
public:
Son(int a, int b) {
this->a= new int(a);
this->b= new int(b);
}
Father* operator+(Father* other) {
//此处如何书写?
}

private:
int *a= nullptr;
int *b= nullptr;
};

int main() {
Father* son1 = new Son(1, 2);//图形1
Father* son2 = new Son(3, 4);//图形2
auto son3=son1+
son2 ; //报错,无法实现
}

  • 写回答

4条回答 默认 最新

  • 快乐鹦鹉 2022-08-31 20:54
    关注
    class Father
    {
    public:
    virtual Father* operator+(Father*) = 0;
    };
    
    class Son:public Father
    {
    public:
    Son(int a, int b) {
    this->a= new int(a);
    this->b= new int(b);
    }
    Father* operator+(Father* other) {
        Son *p = (Son*)other;
       *a += *(p->a);
       *b += *(p->b);
       return this;
    }
    
    private:
    int *a;
    int *b;
    };
    
    int main() {
    Father* son1 = new Son(1, 2);//图形1
    Father* son2 = new Son(3, 4);//图形2
    auto son3=*son1+son2 ; 
    return 0;
    }
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 8月31日

悬赏问题

  • ¥15 求一份STM32F10X的I2S外设库
  • ¥15 android 打包报错
  • ¥15 关于stm32的问题
  • ¥15 ncode振动疲劳分析中,noisefloor如何影响PSD函数?
  • ¥50 寻找fpga的benchmark
  • ¥50 如何在arduino上,实现用4×4矩阵键盘按键控制2004显示屏输出图中显示功能的代码?
  • ¥15 P1口接8个发光二极管,利用定时计数器1编写程序
  • ¥20 keil5编译找不到.h文件该如何解决
  • ¥15 安卓EVS如何开启服务正常实现功能
  • ¥15 canal读取mysql时报错