C ++使用operator int()而不是operator +

时间:2016-07-28 06:47:48

标签: c++ operator-overloading

我试图理解为什么调用operator int()而不是定义的operator+

class D {
    public:
        int x;
        D(){cout<<"default D\n";}
        D(int i){ cout<<"int Ctor D\n";x=i;}
        D operator+(D& ot){ cout<<"OP+\n"; return D(x+ot.x);}
        operator int(){cout<<"operator int\n";return x;}
        ~D(){cout<<"D Dtor "<<x<<"\n";}
};

void main()
{
    cout<<D(1)+D(2)<<"\n";
    system("pause");
}

我的输出是:

int Ctor D
int Ctor D
operator int
operator int
3
D Dtor 2
D Dtor 1

1 个答案:

答案 0 :(得分:9)

您的表达式D(1)+D(2)涉及临时对象。因此,您必须将operator+的签名更改为const-ref

#include <iostream>
using namespace std;

class D {
    public:
        int x;
        D(){cout<<"default D\n";}
        D(int i){ cout<<"int Ctor D\n";x=i;}
        // Take by const - reference
        D operator+(const D& ot){ cout<<"OP+\n"; return D(x+ot.x);}
        operator int(){cout<<"operator int\n";return x;}
        ~D(){cout<<"D Dtor "<<x<<"\n";}
};

int main()
{
    cout<<D(1)+D(2)<<"\n";
}

打印:

int Ctor D
int Ctor D
OP+
int Ctor D
operator int
3
D Dtor 3
D Dtor 2
D Dtor 1

在找到正确的重载时调用operator int,以便将其打印到cout