c++中的多态加号

Polymorphic plus sign in C++?

本文关键字:多态 c++      更新时间:2023-10-16

我了解多态和继承如何在c++中工作,但我的问题是:如何使操作符多态为以下具体示例?

假设我有一个Foo类和两个Foo实例,fooA和fooB。我想重新定义加号操作符,以便"fooA + fooB;"执行特定于Foo实例的操作(无论该操作是什么)。函数原型是什么样子的?这让我很困惑,因为我习惯了以字母开头的函数…如有任何帮助,我将不胜感激。

顺便说一下,这不是一个家庭作业问题——更像是一个奇迹(我正在考虑Ruby中的多态性)。

示例来自http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/cplr318.htm:

#include <iostream>
using namespace std;
class complx 
{
      double real, imag;
public:
      complx(double real = 0., double imag = 0.); // constructor
      complx operator+(const complx&) const;      // operator+()
};
// define constructor
complx::complx(double r, double i)
{
      real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+(const complx& c) const
{
      complx result;
      result.real = this->real + c.real;
      result.imag = this->imag + c.imag;
      return result;
}
int main()
{
      complx x(4,4);
      complx y(6,6);
      complx z = x + y; // calls complx::operator+()
}

const Foo operator+(const Foo& a, const Foo& b)为正确签名。如果数据是私有的,并且没有mutator函数(即"setter"),则它需要是友元函数。

操作符应该是全局函数而不是成员,以便将第一个形参强制为您的类型。例如,如果int可以被强制为Foo,那么使用上面的签名是合法的:1 + foo .

编辑:代码演示为什么操作符+应该是全局的…

struct Foo {
    int i;
    Foo(int i) : i(i) {}
    const Foo operator+(const Foo& a) {
        return Foo(this->i + a.i);
    }
};
int main() {
    Foo f(5);
    f + 1;
    1 + f; // g++ 4.5 gacks here.
    return 0;
}

错误如下:

main.cpp: In function ‘int main()’:
main.cpp:14:9: error: no match for ‘operator+’ in ‘1 + f’

对于二进制+,您需要某种形式的双分派,而不是由c++开箱支持。有几种实现方法这些都有各种各样的缺点。不管你怎么实现双调度本身,对于n不同的派生类型,您将需要n2不同的函数