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

标签 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

最佳答案

您的表达式 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/

相关文章:

c++ - 如何安装系统范围的 nuget 包?

c++ - memcpy c++ - 崩溃

c++ - 本地化基于 MFC 的 DLL?

Perl 重载 @{} 以便您可以为 foreach() 提供一个对象

c++ - 类构造函数、析构函数和运算符重载的实用函数

c++ - kernel.cpp 在制作 kernel.o 时显示错误和 Makefile 错误

c++ - 在 C++ 中重载运算符时,如何解决从 'const double*' 到 'double*' 的无效转换

c++ - 非成员运算符重载是什么意思

C++ + 运算符的这种用法叫什么?目的是什么?

c++ - Netbeans : error while loading shared libraries: libicuuc. so.50:无法打开共享对象文件:没有这样的文件或目录