为什么这是打印"operator + operator +"输出?有人可以对此有所了解吗?

Why this is printing "operator + operator +" as out put? Could somebody please shed some light on this?

本文关键字:operator 了解 输出 为什么 打印      更新时间:2023-10-16

为什么要将"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
}

cout<" double "应为cout << " double "。我很惊讶能按原样编译。

奇怪的是,它与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,那么关注警告可能是件好事。