运算符重载(对象添加)

Operator overloading (object addition)

#include "stdafx.h"
#include "iostream"
using namespace std;

class complex
{
    int real;
    int img;
public:
    complex(int x = 0, int y = 0)
    {
        cout << "Inside Prama" << endl;
        real = x;
        img = y;
    }
    complex operator+(complex x)
    {
        complex temp;
        temp.real=real + x.real;
        temp.img=img + x.img;
        return temp;
    }
    void display()
    {
        cout << real << ' ' << img << endl;
    }
};

int main()
{
    class complex c1(5,6), c2(7,8),c3(7,7),c4;
    c1.display();
    c2.display();
    c3.display();
    c4 = c1+c2+c3;
    c4.display();
    return 0;
}

以上运算符重载代码的输出如下:

为什么在添加 objects.I 时调用参数化构造函数,我不明白

的原因

只是总结评论...

这里

complex operator+(complex x)
{
    complex temp;
    temp.real=real + x.real;
    temp.img=img + x.img;
    return temp;
}

complex temp; 调用构造函数,这就是您看到的输出。通常你会将 x 作为 const 引用传递以避免复制,但无论如何你都需要一个副本,你可以使用 x:

complex operator+(complex x)
{
    x.real +=real;
    x.img +=img;
    return x;
}

这只会在您调用运算符时调用编译器生成的复制构造函数。


还有更多细节需要考虑。使用 x 而不是制作本地副本会抑制 named return value optimization. Also it is common to implement operator+ in terms of operator+= and operator+ can be a free function then. Note that operator+= can be more efficient, because no copy is needed at all. For more details on operator overloading in general I refer you to What are the basic rules and idioms for operator overloading?


PS:到目前为止,“参数化构造函数”是我只在糟糕的误导性教程中看到的一个术语。这不是一个官方术语。这里的相关术语是default constructorcomplex(int x = 0, int y = 0) 是默认构造函数,因为它可以不带参数调用。这是一个很好的例子,说明了为什么“参数化构造函数”没有传达很多含义并且具有误导性。