c++如何正确声明另一个类的友元类方法

标签 c++ friend friend-function

考虑以下示例。

class A
{
    int member;
};

class B
{
    A& a_ref;
    void manipulate()
    {
        a_ref.member++;
    }
};

现在,很明显,B::manipulate 无法访问 a_ref。我想允许(仅)class B 获取(引用)A::member。我知道存在 friend 关键字,但我不知道如何正确使用它。我的意图是,我可以将 B::manipulate 实现更改为这个

int& A::only_B_can_call_this() // become friend of B somehow
{
    return member;
}

void B::manipulate()
{
    a_ref.only_B_can_call_this()++;
}

最佳答案

B 成为 friend :

class A
{
    int member;
    friend /*class*/ B;  // class is optional, required if B isn't declared yet
};

请注意,friend 是反模式 - 如果某些内容是 private,则可能不应访问它。你想达到什么目的?为什么 A 不是独立的?为什么另一个类需要访问它的内部数据?

如果您对这些问题有有效的答案/原因,请使用 friend 。

关于c++如何正确声明另一个类的友元类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32561001/

相关文章:

C++ 头文件 - 包含什么

c++ - Friend 成员函数可以在单独的文件中使用吗?

c++ - Clion c++ 中友元函数的错误

c++ - 如何在将内部类作为参数的命名空间中声明友元函数?

c++ - 获取 char 的十进制 ascii 值

c++ - 如何在C++原生dll中同时返回整数和char *变量?

c++ - 为什么在C++中调用d1=d2+d3语句的拷贝构造函数?

java - Android OOP 设计基础

c++ - 友元函数是否违反封装?

c++ - 为什么在多文件中使用类声明友元函数时出现错误类未定义?