我试着为<<-operator-overloading写一个简单的例子。以前,我从来没有用过“朋友”这个关键词。但没有它,它就不能工作。我做错了什么,或者为什么我需要在这里的朋友关键字?
class rational{
public:
rational(double num, double count)
: n(num),c(count){}
rational& operator+=(const rational& b){
this->n+= b.n;
this->c+= b.c;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const rational& obj)
{
std::cout << obj.n << "," << obj.c << std::endl;
return os;
}
private:
double n;
double c;
};谢谢
发布于 2016-07-28 22:13:15
您希望流式传输其内部不能通过其类的公共接口访问的对象,因此操作符无法访问它们。然后,您有两个选择:要么将一个公共成员放入执行流式传输的类中
class T {
public:
void stream_to(std::ostream& os) const {os << obj.data_;}
private:
int data_;
};并从运算符调用它:
inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
obj.stream_to(os);
return os;
}或者使操作员成为friend
class T {
public:
friend std::ostream& operator<<(std::ostream&, const T&);
private:
int data_;
};这样它就可以访问类的私有部分:
inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
os << obj.data_;
return os;
}发布于 2016-07-28 22:07:27
你没有犯任何错误。friend关键字使您的operator<<()实现能够访问您的类的private (以及protected,如果有)成员。
注意,因为它是一个朋友,这里的operator<<()隐式地是一个自由函数,而不是一个成员函数(如果它是一个成员函数,它已经可以访问private的东西了!)。因为它只在类中声明和定义,所以只能通过依赖于参数的查找来找到它,但这对于operator<<来说是很好的,而且您还不必担心这个细节。
发布于 2016-07-28 22:02:37
您将在类中声明和定义运算符,因此如果没有friend,它将具有隐式的rational类型的第一个操作数。如果你在类的外部声明了运算符,你就不会有这样的问题,但是你就不能访问n和c了。
https://stackoverflow.com/questions/38638670
复制相似问题