C++使用运算符int()而不是运算符+

C++ using operator int() instead of operator+

本文关键字:运算符 int C++      更新时间:2023-10-16

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

class D {
    public:
        int x;
        D(){cout<<"default Dn";}
        D(int i){ cout<<"int Ctor Dn";x=i;}
        D operator+(D& ot){ cout<<"OP+n"; return D(x+ot.x);}
        operator int(){cout<<"operator intn";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

表达式D(1)+D(2)包含临时对象。所以你必须把你的operator+签名改成const-ref

#include <iostream>
using namespace std;
class D {
    public:
        int x;
        D(){cout<<"default Dn";}
        D(int i){ cout<<"int Ctor Dn";x=i;}
        // Take by const - reference
        D operator+(const D& ot){ cout<<"OP+n"; return D(x+ot.x);}
        operator int(){cout<<"operator intn";return x;}
        ~D(){cout<<"D Dtor "<<x<<"n";}
};
int main()
{
    cout<<D(1)+D(2)<<"n";
}

它打印:

int Ctor Dint Ctor D操作+int Ctor D运算符int3.D Dtor 3D Dtor 2D Dtor 1

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