C++:授予私有运算符 "passing through" 一个朋友 class 的访问权限,可能吗?
C++: grant access to private operator "passing through" a friend class, possible?
假设我已经定义了这两个 classes:
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
我的问题是:当且仅当左值是列表中的引用(即 friend class of 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; }
};
现在忘记你曾经见过这个,因为无论如何这可能是一个非常糟糕的设计。
假设我已经定义了这两个 classes:
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
我的问题是:当且仅当左值是列表中的引用(即 friend class of 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; }
};
现在忘记你曾经见过这个,因为无论如何这可能是一个非常糟糕的设计。