作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有三个不同的类 A
、B
和 C
。我能否创建一个函数 f
,它可以访问 A
的私有(private)成员,并让 f
只能由 B
调用>(而不是 C
)?
我正在寻找一种替代方法,让 B
类成为 A
类的 friend 。
最佳答案
当然。使有问题的友元函数以 private
构造函数作为参数类,其中 B
是唯一的 friend
。示例:
#include <iostream>
class A;
class B;
template <typename T>
class Arg {
friend T; // only T can make Arg<T>
};
void foo(A& a, Arg<B> ); // only B can make a Arg<B>
// so foo is only callable by B
class B {
public:
void bar(A& a) { // public for demonstration purposes
foo(a, Arg<B>{}); // but this can just as easily be private
}
};
class A {
friend void foo(A&, Arg<B>); // foo can access A's internals
int x;
public:
void print() { std::cout << x << '\n'; }
};
void foo(A& a, Arg<B> ) { a.x = 42; }
int main() {
A a;
B b;
b.bar(a);
a.print();
}
foo
是A
的 friend
,只能被B
使用。
关于c++ - 只能由特定类使用的类的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760748/
有一条(相对)众所周知的 Perl 公理:“只有 Perl 可以解析 Perl”。我想知道 Perl 6 是否仍然如此? 扩大讨论...考虑到 PyPy 最近的更新,我想到了这个问题。 Perl 独特
这是设置。在上一个问题中,我发现我可以通过子组件中的状态传递对象属性,然后使用 componentDidUpdate 获取该对象属性。在这种情况下,状态和属性都称为到达。 这是基本代码... expo
我运行的是 10.5.2 社区版。我已经标记了 源/主要/资源 作为源目录。我可以右键单击并“编译”某些文件,据我所知,这意味着 IDE 将文件复制到与发送类文件的“com.mydomain.pack
我是一名优秀的程序员,十分优秀!