C++正在重载我的重载运算符

C++ is overloading my overloaded operators?

本文关键字:重载 我的 运算符 C++      更新时间:2023-10-16

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

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 data;
  public:  
    Int (){data = 0; };
    Int (int size){ data = size; };
    friend int operator+(Int, Int);
};
int operator+(Int lInt, Int rInt) 
{   cout <<"first version. "; 
    return rInt.data + lInt.data; 
}
int main(int argc, char *argv[]) {
    Int int1 = 1;
    cout <<  int1 + int1 <<endl; // prints "first version. 2"
    cout <<  3 + int1 << endl;   // prints "first version. 4"
    cout <<  int1 + 3 << endl;   // prints "first version. 4"
}

我的重载+运算符(用于接受两个对象)如何能够接受int和object。它是如何获取object和int的?我希望我没有忽视一些愚蠢的显而易见的东西!

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

Int (int size){ data = size; };

因此编译器可以计算出Int + int应该调用Int + Int(int)

如果出于任何原因,您都不希望这样做,那么您可以将构造函数标记为explicit

罪魁祸首是这个家伙:

Int (int size){ data = size; };

由于它没有标记为explicit,因此这是一个隐式构造函数,并且在您有int但函数(或运算符)需要Int的上下文中,编译器会自动向它推送调用。

例如,编译器解析

cout <<  3 + int1 << endl;

cout <<  Int(3) + int1 << endl;

自动。

使用explicit关键字来强制这类代码更加显式通常是一个好主意,但是,应该提到的是,隐式构造在非常突出的代码中大量使用,最显著的是C++标准库,例如,std::string可以由const char*隐式构造。这是在方便和清晰之间的权衡。