c++ - 在 C++ 中使用友元函数

标签 c++ class friend friend-class

刚刚阅读有关友元函数的内容,我正在尝试使用 B 类中的友元函数“Print”访问 A 类中的私有(private)变量“number”。我正在使用 Visual Studio。编译我的代码给了我很多不同的错误,例如:

C2011: 'A' : 'class' type redefinition
C2653: 'B' : is not a class or namespace name

请对我有耐心,并展示实现我的目标的正确方法。

这是我的文件 啊:

class A
{
public:
    A(int a);
    friend void B::Print(A &obj);
private:
    int number;
};

A.cpp:

#include "A.h"

A::A(int a)
{
    number=a;
}

B.h:

#include <iostream>
using namespace std;
#include "A.h"
class B
{
public:
    B(void);
    void Print(A &obj);
};

B.cpp:

#include "B.h"

B::B(void){}

void B::Print(A &obj)
{
    cout<<obj.number<<endl;
}

main.cpp:

#include <iostream>
#include <conio.h>
#include "B.h"
#include "A.h"

void main()
{
    A a_object(10);
    B b_object;
    b_object.Print(A &obj);
    _getch();
}

最佳答案

... 其次,您可能需要在 A.h 头文件中对类 B 进行前向声明,以将 B 引用为友元:

#ifndef _A_H_
#define _A_H_
class B;

class A
{
     friend class B;
};
#endif

更新
我目前不太确定是否可以将成员函数声明为友元,我会看看。

无法创建成员函数 friend 声明,您可以将全局函数或整个类声明为友元,另请参阅:C++ ref, Friendship and inheritance .

一般来说,使用 friend 根本不是一个好的设计理念,因为它将类强耦合在一起。更好的解决方案是耦合接口(interface)(无论如何都不需要公开可见)。
在极少数情况下,这可能是一个很好的设计决策,但这几乎总是适用于内部细节。

关于c++ - 在 C++ 中使用友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13884788/

相关文章:

c++ - friend 父类无法访问子类中的私有(private)构造函数

c++ - 将多个整数打包成一个 64 位整数

c++ - 字符串统计函数

python - "if x in self:"是什么意思?

c++ - 删除非指针 vector 中的指针

c++ - friend 模板运算符<<无法访问类的保护成员

c++ - 具有过度约束类的噩梦表达式树

c++ - 字符数组分配

c++ - 强制在某个静态字段之前初始化全局变量

c++ - 在结构中启动数组时遇到问题