简体   繁体   English

用于运算符重载的friend关键字

[英]friend keyword for operator overloading

I tried to write an simple example for the <<-operator-overloading. 我试着为<< - operator-overloading写一个简单的例子。 Before, i've never used the keyword "friend". 之前,我从未使用过关键字“朋友”。 But it does not work without it. 但没有它它就行不通。 What is the mistake i did or why do i need the friend keyword here? 我做了什么错误或为什么我需要朋友关键字?

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;
};

Thanks 谢谢

You didn't make any mistake. 你没有犯任何错误。 The friend keyword gives your operator<<() implementation access to private (and protected , if you had any) members of your class. friend关键字为您的operator<<()实现访问您的类的private (并且protected ,如果有的话)成员。

Note that because it's a friend, operator<<() here is implicitly a free function and not a member function (if it were a member function, it could access private things already!). 请注意,因为它是朋友,所以operator<<()这里隐式地是一个自由函数而不是一个成员函数(如果它是一个成员函数,它可以访问private东西!)。 Because it's declared and defined only inside the class, it can only be found by argument-dependent lookup, but this is fine for operator<< and is a detail you don't have to worry about yet. 因为它只在类中声明和定义,所以它只能通过参数依赖查找来找到,但这对于operator<<是好的,并且是一个你不必担心的细节。

You are declaring and defining the operator inside the class, thus without friend it has an implicit first operand of type rational . 您在声明和定义在类中操作,因此没有friend有型的隐式第一个操作数rational You wouldn't have such problem if you had declared the operator outside the class, but then you wouldn't have access to n and c. 如果您在类外声明了运算符,则不会出现此类问题,但是您将无法访问n和c。

You want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. 您希望流式传输其内部不能通过其类的公共接口访问的对象,因此操作员无法获取它们。 Then you have two choices: Either put a public member into the class which does the streaming 然后你有两个选择:将公共成员放入进行流式处理的类中

class T {
  public:
    void stream_to(std::ostream& os) const {os << obj.data_;}
  private:
    int data_;
};

and call that from the operator: 并从运营商那里打电话:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   obj.stream_to(os);
   return os;
}

or make the operator a friend 或者让操作员成为friend

class T {
  public:
    friend std::ostream& operator<<(std::ostream&, const T&);
  private:
    int data_;
};

so that it can access the class' private parts: 这样它就可以访问班级的私人部分:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   os << obj.data_;
   return os;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM