c++ - 为什么这两个重载函数的声明方式不同?

标签 c++ operator-overloading

我目前正在阅读有关重载函数的内容,并且在我的书中遇到了两个示例,但没有解释为什么它们的创建方式不同。

第一个例子像这样重载“==”运算符:

bool operator==(const Passenger &x, const Passenger&y){
//.......implementation details hidden
}

虽然第二个例子像这样重载了“<<”运算符:

ostream& operator << (ostream &out, const Passenger& pass){
//.......implementation details hidden
return out;
}

为什么第二个示例使用了“&”符号而第一个示例没有?为什么我们不能只使用 ostream operator 而不是 ostream& operator?为什么 bool 运算符不使用“&”?

最佳答案

您需要 << 返回的值运算符作为引用,因此它实际上返回原始的 ostream对象而不是对象的拷贝。这就是为什么它可以将多个 << 串起来的原因。一起调用:

std::cout << "Hey"; // Prints "Hey" and returns cout
std::cout << passenger; // Calls custom operator and returns cout
std::cout << "What?"; // Prints "What?" and returns cout

相当于:

std::cout << "Hey" << passenger << "What?";

通过引用返回 bool 值没有多大意义,因为您不希望能够操纵 == 返回的值运营商。

关于c++ - 为什么这两个重载函数的声明方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28615913/

相关文章:

添加新函数引起的 C++ 运行时错误(从未超出其定义使用)

c++ - C++中的自定义运算符重载而无开销

从另一个命名空间内访问 C++ 全局命名空间

c# - 运算符重载多态返回泛型集合

C++ 类和重载运算符

c++ - 使用 nlohmann C++ 库读取 json 对象数组

c++ - 将 unsigned char* 转换为 unsigned char**(不带 &)

c++ - 用 1 和 0 填充一个大矩阵 - 六个嵌套循环

c++ - eigen::select() 的奇怪行为

c++ - 运算符 new[] 不接收额外的字节