为什么这是打印“operator + operator +”?我的期望是“操作员+双操作员+”。有人可以对此有所了解吗?
#include<iostream>
using namespace std;
struct mydata{
int mx;
mydata(int x = 0){}
mydata operator+(const mydata& rhs){
cout<<" operator + ";
mydata temp(rhs);
return temp;
}
operator int() const{cout<<" int "; return mx; }
operator double() const{cout<" double "; return mx; }
};
int main(){
mydata d;
mydata r = d + mydata(5); // L1
5 + (double)d; // L2
d + d; // L3
}
答案 0 :(得分:1)
cout<" double "
应为cout << " double "
。
我很惊讶按原样编译。
答案 1 :(得分:0)
奇怪的是,这会编译并运行VS2008
并产生OP的答案,这很容易错过警告:
warning C4552: '<' : operator has no effect; expected operator with side-effect
然而,GCC在编译时确实会爆炸(这实际上很不错):
test.cpp: In member function 'mydata::operator double() const':
test.cpp:14: error: no match for 'operator<' in 'std::cout < " double "'
test.cpp:14: note: candidates are: operator<(const char*, const char*) <built-in>
test.cpp:14: note: operator<(void*, void*) <built-in>
因此,如果OP正在使用VS
,那么关注警告可能会很好。