C++正在重载我的重载运算符
C++ is overloading my overloaded operators?
我今天注意到了一些事情。如果我创建三个版本的重载+运算符来处理每个组合(对象+基元、基元+对象、对象+对象),那么一切都会按预期执行:
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的?我希望我没有忽视一些愚蠢的显而易见的东西!
您已经定义了从int
到Int
:的隐式转换
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*
隐式构造。这是在方便和清晰之间的权衡。
相关文章:
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 如何为我的类实现/重载二进制运算符
- 什么时候可以使用常量装饰调用我的重载函数?
- 我的运算符重载没有在我的 int main 中返回?
- 如何让我的重载<<运算符打印出我的函数?
- c++运算符重载-我实际返回的操作数类型是什么
- 我的重载运算符 == 中的 C++ 参数太少
- 我的重载函数有什么问题?
- 如何重载运算符<<显示我的列表
- 我的移动分配操作程序重载的分段错误
- 为什么我的重载 + 运算符在返回时会产生"Invalid address specified to RtlValidateHeap"错误?
- 无法使用"enable_if"和"is_base_of"将模板函数"operator+"的重载限制到我的类层次结构
- 我的重载后增量方法无法按预期工作。为什么?
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- 我的运算符重载友元函数无法理解模板类型 T 的问题
- 运算符重载如何工作,为什么在我的情况下不起作用?
- C++正在重载我的重载运算符
- 有人可以指出为什么我的变量无法识别以及为什么我不能重载我的运算符吗