我试图理解为什么调用 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
最佳答案
您的表达式 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
时被调用。
关于C++ 使用 operator int() 而不是 operator+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38628949/