C++ C++;重载是我的重载运算符吗?

C++ C++;重载是我的重载运算符吗?,c++,operator-overloading,implicit-conversion,C++,Operator Overloading,Implicit Conversion,我今天注意到了一些事情。如果我创建三个版本的重载+运算符来处理每个组合(对象+基元、基元+对象、对象+对象),则所有操作都会按预期执行: class Int { int data; public: Int (){data = 0; }; Int (int size){ data = size; }; friend int operator+(Int, Int); friend int operator+(int, Int); friend int

我今天注意到了一些事情。如果我创建三个版本的重载+运算符来处理每个组合(对象+基元、基元+对象、对象+对象),则所有操作都会按预期执行:

class Int
{ int data;
  public:  
    Int (){data = 0; };
    Int (int size){ data = size; };
    friend int operator+(Int, Int);
    friend int operator+(int, Int);
    friend int operator+(Int, int);
};
int operator+(Int lInt, Int rInt) 
{   cout <<"first version. "; 
    return rInt.data + lInt.data; 
}
int operator+(int lInt, Int rInt) 
{   cout <<"second version. "; 
    return rInt.data + lInt; 
}
int operator+(Int lInt, int rInt)
{   cout <<"third version. ";
    return lInt.data + rInt;
}
int main(int argc, char *argv[]) {

    Int int1 = 1;

    cout <<  int1 + int1 <<endl; // prints "first version. 2"
    cout <<  3 + int1 << endl;   // prints "second version. 4"
    cout <<  int1 + 3 << endl;   // prints "third version. 4"
}
class Int
{int数据;
公众:
Int(){data=0;};
Int(Int size){data=size;};
友元整数运算符+(整数,整数);
友元整数运算符+(整数,整数);
友元整数运算符+(整数,整数);
};
int运算符+(int lInt,int rInt)

{cout罪魁祸首是这个家伙:

Int (int size){ data = size; };
因为它没有被标记,这是一个隐式构造函数,编译器将在您有
int
但函数(或运算符)需要
int
的上下文中自动推送对它的调用

例如,编译器解析

cout <<  3 + int1 << endl;

cout您已经定义了从
int
int
的隐式转换:

Int (int size){ data = size; };
因此编译器可以计算出
Int+Int
应该调用
Int+Int(Int)


如果您不想这样做,无论出于何种原因,您都会将构造函数标记为
explicit

啊!我明白了!但是如果构造函数没有返回值,std::cout如何得到答案?@Jeff Russ:“返回值”构造函数的参数是被构造的对象。
的参数好了,明白了。非常感谢!!也感谢你。现在我明白了!
cout <<  Int(3) + int1 << endl;
Int (int size){ data = size; };