c++ - 我应该如何在嵌套类中正确使用友元声明?

标签 c++ class oop c++11 friend

例如,假设我编写了如下代码:

class A
{
private:
    class B
    {
    private:
        int a;
        friend int A::foo(B &b);
    };
    int foo(B &b)
    {
        return b.a;
    }
};

aB是私有(private)的,使用 a在函数中 fooA , 我会用 friend这样foo实际可以访问a .

但是这段代码给出了无法访问 a 的错误.代码有什么问题,我应该如何在保留a的情况下更改代码私有(private)和A不是 B 的 friend ?或者有更好的方法吗?

最佳答案

如果您只想获取B 类的a,您需要一个getter 函数。这应该是最简单的方法。

class B
{
private:
    int a;
public:
    // provide getter function
    const int& getMember_a()const { return a; }
};

foo 函数中

const int& foo(const B &b)const 
{
    return b.getMember_a(); // call the getter to get the a
}

关于你的代码问题;在 B 类的 friend int A::foo(B &b); 行,它不知道函数 A::foo .因此我们需要在B类之前转发声明int foo(B &);。然后是问题; A::foo(B &) 是否知道 B。也没有。但幸运的是,C++ 也允许通过前向声明类来拥有不完整的类型。这意味着,循序渐进,您可以实现您想要的目标。

class A
{
private:
    class B;      // forward declare class B for A::foo(B &)
    int foo(B &); // forward declare the member function of A
    class B
    {
    private:
        int a;
    public:
        friend int A::foo(B &b);
    };
};
// define, as a non-member friend function
int A::foo(B &b)
{
    return b.a;
}

关于c++ - 我应该如何在嵌套类中正确使用友元声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019191/

相关文章:

python - 在两个相关类中使用继承的最佳方式是什么

oop - 需要帮助理解 Go 中的 `map[String]type` 行为

c# - 如何在托管代码 (C#) 中从 native 代码 (C++) 获取字符串数组

c++ - 怎么了?如何更改 "sum1"顺序?

python - 为什么Python中类属性的赋值行为类似于实例变量的赋值?

python - 类方法作为模型函数和类方法作为 scipy.optimize 的优化函数

java - 在一种方法中设置变量的值并在另一种方法中打印

php - PHP 中的美元符号是什么意思?

c++ - SHA-2 算法的字节顺序乐趣

c++ - `using namespace ...` 会增加编译时间还是会以某种方式影响性能?