c++ - 友元函数看不到私有(private)成员变量

标签 c++ operator-overloading

我正在尝试使用友元函数重载 << 运算符,但由于某种原因它没有看到私有(private)成员变量。任何关于为什么会发生这种情况的想法都会很有帮助。

这是头文件

    class Set
    {
private:
    struct Node
    {
        int val;
        Node* link;
    };

    Node *cons(int x, Node *p);
    Node *list;


public:
    Set() {list = NULL;}
    bool isEmpty() const;
    int size() const;
    bool member (int x) const;
    bool insert (int x);
    bool remove (int x);
    void print() const;
    const Set operator+(const Set &otherSet)const;
    const Set operator*(const Set &otherSet)const;
    Node* getSet()const{return list;}
    void setList(Node *list);
    friend ostream& operator <<(ostream& outputStream, const Set &set);
    };

这是函数定义。

    ostream& operator <<(ostream& outputStream, const Set &set)
    {
              Node *p;
              p = list;
              outputStream << '{';
              while(p->link != NULL)
              {
                outputStream << p->val;
                p = p->link;
              }
              outputStream << '}';
              return outputStream;
    }

最佳答案

问题不在于 Node 的可访问性,而在于它的范围:非限定类型名称不会通过友元进入范围 - 你应该使用 Set::Node 相反。

list 变量也是如此:它应该是 set.list

有了这两个变化,your code compiles fine on ideone .

关于c++ - 友元函数看不到私有(private)成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505600/

相关文章:

c++ - 重载 << 运算符来存储数据

c++ - 在 C++ 头文件/实现文件中放置#undef 指令的正确方法

c++ - boost::archive::xml_oarchive 中的 class_id

c++ - 在 C++ 中运算符重载后递增

c++ - 为哈希表获取和设置正确重载 [bracket] 运算符

c++运算符重载的多态性

c++ - 模板化运算符的奇怪行为<<

c++ - 派生对象可以转换为 C++ 模板类中的基引用吗?

c# - 避免非托管 c++、c++/cli 和 c# 代码之间的 std::deque 迭代器不可取消引用错误

c++ - 将秒(时钟)转换为十进制格式