【发布时间】:2016-06-11 15:03:23
【问题描述】:
我试图编写一些运算符重载函数,尤其是 << 运算符,以将其与自定义类和 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?
【问题讨论】:
标签: c++ class operator-overloading operators