C++使用运算符int()而不是运算符+
C++ using operator int() instead of operator+
我试图理解为什么调用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
时被调用。
相关文章:
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 运算符 += 应用于 std::valarray<int*>
- 我的运算符重载没有在我的 int main 中返回?
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 使用算术运算符时如何避免从 char 到 int 的隐式转换
- ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 运算符[]和运算符int()的不明确重载
- 二进制 '[':未找到采用 'const SortableVector' 类型的左操作数的运算符<int>
- 是否可以为带有 std:string 和 std::vector 的 std::map 重载<<运算符<int>?
- GCC 无法区分运算符++() 和运算符++(int)
- 是否可以完全模拟虚拟运算符++(int)?
- 运算符++()和运算符++(int)之间的区别是什么
- 重载c++运算符int/foat(.)
- 筛选的const_iterator运算符++(int)
- static_cast和interpret_cast的转换运算符int()失败
- 使用 google mock 模拟转换运算符 int()
- 重载对象前面带有数字的运算符+(int)
- 运算符 [](int i) 中的边界检查
- C++使用运算符int()而不是运算符+