如何让一个 class public 只对另一个 class
How to make a class public only to another class
我在 C++ 中有两个不同的 类,Node 和 Graph。我想通过图中的方法访问 Node 的内容,而不是 public,我该怎么做?
您可以使用 friend
声明来指定 class
es 或函数,您希望授予对 private
和 protected
成员的完全访问权限。
示例:
class Node {
// ...
private:
friend class Graph;
int x;
};
class Graph {
public:
void foo(Node& n) {
n.x = 1; // wouldn't work without `friend` above
}
};
int main() {
Graph g;
Node n;
g.foo(n);
}
我在 C++ 中有两个不同的 类,Node 和 Graph。我想通过图中的方法访问 Node 的内容,而不是 public,我该怎么做?
您可以使用 friend
声明来指定 class
es 或函数,您希望授予对 private
和 protected
成员的完全访问权限。
示例:
class Node {
// ...
private:
friend class Graph;
int x;
};
class Graph {
public:
void foo(Node& n) {
n.x = 1; // wouldn't work without `friend` above
}
};
int main() {
Graph g;
Node n;
g.foo(n);
}