gpt4 book ai didi

c++ - 只能由特定类使用的类的友元函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:01:07 25 4
gpt4 key购买 nike

我有三个不同的类 ABC。我能否创建一个函数 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();
}

fooA friend ,只能被B 使用。

关于c++ - 只能由特定类使用的类的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com