我正在尝试编写一些运算符重载函数,尤其是 <<
运算符将其与自定义类和 std::ofstream
一起使用对象,但我对网上找到的各种示例中使用的语法感到有点困惑。例如,让我们考虑 operator<<
作为简单自定义类的非成员函数重载:
#include <fstream>
class Example {
public:
int first;
int second;
};
// I found this kind of operator on the Internet
std::ofstream& operator<< (std::ofstream& out, Example obj) {
out << obj.first << endl << obj.second;
return out;
}
int main() {
Example a={1,2};
std::ofstream out;
out.open("test");
out << a;
out.close();
}
我真的不明白为什么它应该返回 std::ofstream&
正常工作。我尝试使用以下运算符
void operator<< (std::ofstream& out, Example obj) {
out << obj.first << endl << obj.second << endl;
}
而且效果很好。我的意思是,不能 out << obj;
解释为 operator<< (out , obj);
?为什么它必须返回一些东西,因为我正在传递对 std::ofstream
的引用对象?
当我试图写一个 operator=
时,同样的疑问出现了作为自定义类的成员函数重载,如下面的简单示例
class Custom{
public:
int up;
int down;
Custom& operator= (Custom a) {
up=a.up;
down=a.down;
return *this;
}
};
我对赋值运算符使用了复制交换惯用语,所以不要太介意运算符定义,这只是一个例子。再次,写作
Custom obj1, obj2;
obj1 = obj2;
因为我可以解释 obj1 = obj2;
作为obj1.operator=(obj2)
,为什么返回类型是Custom&
需要而不是 void
?
最佳答案
如果你想能够链operator<<
在一起,你必须使用返回类型(比 std::ostream&
更好的 std::ofstream&
,所以你也可以将它用于 std::cout
等)。
out << a << b;
(out << a) << b;
^^^^^^^^^^
lhs has to be a stream
对于赋值运算符,道理本质上是一样的。 C++ 语法允许您编写许多需要返回类型的表达式,例如:
Custom obj1, obj2, obj3;
(obj1 = obj2) + obj3 ... // assign obj2 to obj1 and work with that...
关于c++ - 运算符重载疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684901/