C++:可以向私人运营商"passing through"朋友类授予访问权限吗?
C++: grant access to private operator "passing through" a friend class, possible?
假设我定义了这两个类:
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; }
};
现在忘记你曾经看到过这个,因为这可能是一个非常糟糕的设计。
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 使用 CTRP 时,是否访问访问父构造函数 UB 中的子属性?
- Lambda 函数,用于调用有权访问类成员的成员函数
- 使用QtCreator,如何在我有权访问ssh的远程服务器上构建我的项目?
- 默认赋值运算符有权访问基类的私有成员
- 访问接口的私有继承如何允许可访问对象访问访问私有访问实现
- 外部必须有权访问类构造函数
- 检查用户名是否有权访问窗口上的文件夹
- 获取从基类指针到具有不同类型的两个派生成员变量的访问权
- 好友有权访问好友的成员,但似乎无法更新好友的成员