【发布时间】:2012-05-31 21:48:27
【问题描述】:
我有一个类Counter,我想重载operator << 以输出Counter 的数据成员。我试图让 ostream 重载一个成员函数:
Counter{
public:
std::ostream& operator<<(std::ostream& outStream, const Counter& c);
private:
int count_;
};
std::ostream& Counter::operator<<(std::ostream& outStream, const Counter& c){
outStream << c.count_;
return outStream;
}
但是g++编译器总是输出同样的错误:
‘std::ostream& Counter::operator<<(std::ostream&, const Counter&)’必须只接受一个参数
但是,如果我将重载函数更改为类的朋友,它工作得很好,像这样:
Counter{
public:
friend std::ostream& operator<<(std::ostream& outStream, const Counter& c);
private:
int count_;
};
std::ostream& operator<<(std::ostream& outStream, const Counter& c){
outStream << c.count_;
return outStream;
}
这是否意味着流运算符重载不能是类的成员函数?
【问题讨论】:
-
它没有必须成为朋友 - 如果你的班级设计得很好,你可以使用公共接口......
-
如果你想访问非公共成员,它必须是朋友,就像任何其他功能一样;
operator<<这里没什么特别的。 -
@ildjarn 但它可以是成员函数吗?
-
@Brian : 不,因为第一个参数必须是流,并且在成员函数中,第一个(隐式)参数始终是指向类类型的指针(即
this)。 -
@ildjarn 我明白了,非常感谢!
标签: c++