【发布时间】:2015-01-29 09:25:56
【问题描述】:
假设有一个 cPoint 类。
class cPoint {
int x, y, z;
};
我想在一个语句中打印所有三个变量。所以,我重载了运算符
friend std::ostream& operator<< (std::ostream &cout, cPoint &p);
std::ostream& operator<< (std::ostream &out, cPoint &p) {
out << p.get_x() << " " << p.get_y() << " " << p.get_z() << std::endl;
return out;
}
有意义吗?
我的问题在于插入运算符(>>)会发生什么。我还重载了它以将 x、y 和 z 的值放入单个语句中。
friend std::istream& operator>> (std::istream &cin, Point &p);
std::istream& operator>> (std::istream &in, Point &p) {
int tmp;
in >> tmp;
p.set_x(tmp);
in >> tmp;
p.set_y(tmp);
in >> tmp;
p.set_z(tmp);
}
清除?
int main() {
cout << p << endl;
cin >> p;
}
我知道如果 operator
但是如果是>>会发生什么。为什么我不能像这样为 >> 返回一个 void:
void operator>> (std::istream &cin, Point &p);
因为 cin >> p 返回 void 或其他内容都没有关系。没有其他操作数可以使用它。这个不清楚。
【问题讨论】:
-
顺便说一句,您应该使用
(std::ostream &out, const cPoint &p)而不是(std::ostream &out, cPoint &p)- 否则您会产生输出运算符修改其cPoint参数的印象。