2

为什么要打印“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
}
4

2 回答 2

1

cout<" double "应该是cout << " double "。我很惊讶按原样编译。

于 2013-02-19T08:06:47.450 回答
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它可能会很好地关注警告。

于 2013-02-19T08:13:40.930 回答