C ++中的多态加号?

时间:2011-09-14 07:25:36

标签: c++ polymorphism

我理解多态性和继承在C ++中是如何工作的,但我的问题是:如何使运算符变为多态以用于以下具体示例?

假设我有一个Foo类和两个Foo实例,fooA和fooB。我想重新定义加号运算符,以便“fooA + fooB;”做一些特定于Foo实例的东西(不管是什么)。函数原型看起来如何?这让我感到困惑,因为我习惯以字母开头的功能......任何帮助都会非常感激。

顺便说一下,这不是一个功课问题 - 更像是一个奇迹(我在考虑Ruby中的多态性)。

3 个答案:

答案 0 :(得分:4)

来自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+()
}

答案 1 :(得分:3)

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

操作符应该是全局函数而不是成员,以便将第一个参数强制转换为您的类型。例如,如果int可以强制转换为Foo,则上述签名是合法的:1 + foo

编辑: 代码演示了为什么operator +应该是全局的......

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’

答案 2 :(得分:1)

对于二进制+,您需要某种形式的双重调度,而不是 由C ++开箱即用。有几种实施方式 这一切都有各种缺点。不管你怎么样 实现双重调度本身,对于 n 不同的派生类型, 你将需要 n 2 不同的功能。