【问题标题】:C++ - Overloading operators that accept abstract classesC++ - 重载接受抽象类的运算符
【发布时间】:2014-05-26 00:22:08
【问题描述】:

我在尝试为我的 C++ 类解决一个简单问题时遇到了一些麻烦。

我有两个类:Component,一个从中继承其他类的抽象类和List,一个具有组件列表的类(它不是模板类)。我想重载operator+。这样当我“添加”两个组件时,它将返回一个包含两个 ComponentsList

我已经这样做了,它没有显示任何错误:

friend List operator +(Component &c1, Component &c2) {
        List l;
        l.push(c1);
        l.push(c2);
        return l;
    }

但是,当我尝试“添加”两个从 Component 继承的类对象时,出现以下错误:

no match for 'operator+' in 'c1 + c2'

这是我添加对象的方法:

Inherited1 c1(1, 2, 3);
Inherited2 c2(1, 3.2, 10);
List l1 = c1+c2;

【问题讨论】:

  • This works 基本上就是你所展示的。这里肯定存在不可重现的问题。
  • 这是个坏主意。除非您实际上是在实现 DSL,否则您应该保留运算符的算术含义。
  • operator + 接收Component&,你发送的是Inherited,它将如何工作?
  • @RakibulHasan,因为它是派生类。
  • 你需要在类外添加函数的定义。

标签: c++ operator-overloading abstract-class


【解决方案1】:

友元函数未在类外定义,因此编译器无法找到 operator+。友元 func operator+ 应该定义在 List 类之外。

由于你没有发布完整的类结构,我假设并尝试了这个:

#include <iostream>
#include <list>

using namespace std;


class Component{

    public:


};

class List{

    list<Component> l;
public:

   void push(Component& c)
   {
       l.push_back(c);
   }
  friend List operator +(Component &c1, Component &c2);

};

class Inherited1:public Component{

    public:
    Inherited1(int x,int y,int z){}

};

class Inherited2:public Component{

    public:
     Inherited2(int x,int y,int z){}  


};

 List operator +(Component &c1, Component &c2) {
        List l;
        l.push(c1);
        l.push(c2);
        cout<<"called"<<endl;
        return l;
    }



int main()
{

    Inherited1 c1(1, 2, 3);
    Inherited2 c2(1, 3.2, 10);
    List l1 = c1 + c2;

    return 0;
}

我假设你的 List 类中有 operator+ func ,如下所示,因为你得到了错误:

错误:“operator+”不匹配(操作数类型为“Inherited1”和“Inherited2”) 列表 l1 = c1 + c2;


class List{

    list<Component> l;
public:

   void push(Component& c)
   {
       l.push_back(c);
   }
  friend  List operator +(Component &c1, Component &c2) {
        List l;
        l.push(c1);
        l.push(c2);
        cout<<"called"<<endl;
        return l;
    }

};

【讨论】:

猜你喜欢
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2015-05-09
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
相关资源
最近更新 更多