c++ - 运算符重载的 friend 关键字

标签 c++

我试图为 <<-operator-overloading 写一个简单的例子。 以前,我从来没有用过“ friend ”这个关键词。但没有它就无法工作。我做错了什么或者为什么我需要这里的 friend 关键字?

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

谢谢

最佳答案

你没有犯任何错误。 friend关键字给你 operator<<()实现访问 private (和 protected,如果有的话)类(class)成员。

注意因为是 friend ,operator<<()这里隐式地是一个自由函数而不是成员函数(如果它是一个成员函数,它已经可以访问 private 东西了!)。因为它只在类内部声明和定义,所以只能通过依赖于参数的查找找到它,但这对 operator<< 没问题。并且是您还不必担心的细节。

关于c++ - 运算符重载的 friend 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38638670/

相关文章:

c++ - 二叉搜索树分割错误

c++ - 对象模型的实现布局

c++ - 使用 Boost.Spirit.Lex 和流迭代器

c++ - 如何将 json 数据从 Poco c++ json 转换为 XML?

c++ - 使用 Makefile 构建时在 Xcode 中忽略的断点

c++ - 运算符 '=' 不匹配(std::array<T, 3> 和 std::initializer_list<T>)

c++ - 使用 && 运算符加入折叠/可变表达式的输出

c++ - 需要有关 C++ v11 类模板中类型约束设计的建议

c++ getline和stringstream

c++ - std::unique_ptr 作为在 std::thread 中运行的参数