C++:可以向私人运营商"passing through"朋友类授予访问权限吗?

C++: grant access to private operator "passing through" a friend class, possible?

本文关键字:访问 访问权 权限 through 可以向 运营商 C++ passing 朋友      更新时间:2023-10-16

假设我定义了这两个类:

class Node
{
    friend class list;
public:
    Node (const int = 0);
    Node (const Node &);
private:
    int val;
    Node * next;
    Node & operator=  (const Node &);
};

class list
{
public:
    list ();                                
    list (const list &);                    
    ~list ();                              
    list & operator+= (const Node &);
    Node & operator[] (const int) const;    
private:
    list & delete_Node (const int);
    Node * first;
    int length;
};

然后,在main.cpp文件中,我有这些行:

list l1;
l1 += 1;
l1 += 41;
l1[1] = 999;    // <-- not permitted: Node::operator= is private

我的问题是:是否有可能授予访问Node::operator=当且仅当左值是列表内的引用(这是Node朋友类),即使main()不是朋友函数?

这个不行,但是这个可以:

class Node
{
    friend class list;
public:
    Node (const int = 0);
    Node (const Node &);
private:
    int val;
    Node * next;
    Node & operator=  (const Node &);
};
class Magic
{
public:
    operator Node&() { return node; }
    Node& operator=(int v) { return list::assign(node, v); }
private:
    friend class list;
    Magic(Node& n) : node(n) {}
    Node& node;
};
class list
{
public:
    Magic operator[] (int) const { return const_cast<Node&>(*first); }
private:
    static Node& assign(Node& n, int v) { n.val = v; return n; }
};

现在忘记你曾经看到过这个,因为这可能是一个非常糟糕的设计。