c++ - 类定义交叉引用时如何声明友元方法?

标签 c++ friend-function

我想定义两个类,A 和 B。A 有一个数据成员,它是一个 B 类对象,并且是类内初始化的。 A 也有一个方法来检索此 B 类型数据成员中的值,并且此方法将被声明为 B 中的友元方法。这是我的代码:

class A{
public:
    int getBValue();
private:
    B b=B(1);
};

class B{
public:
    friend int A::getBValue();
    B(int i):value(i){}
private:
    int value;
};

int A::getBValue(){
    return b.value;
}

不出所料,由于 A 类定义中的未知类型 B,编译失败了。我曾尝试交换源代码中 A 和 B 的定义,结果更糟。有没有办法解决 A 和 B 之间的这个交叉引用问题?

最佳答案

如果这是您所拥有的完整代码,那么问题是编译器在编译类 A 时不知道什么是 B >。解决它的一种方法是创建指向 B 的指针,而不是拥有 B 本身:

啊啊

#ifndef CLASS_A
#define CLASS_A

class B;

class A{
public:
    int getBValue();
private:
    B *b;
};

#endif

B.h

#ifndef CLASS_B
#define CLASS_B

#include "A.h"

class B{
public:
    friend int A::getBValue();
    B(int i):value(i){}
private:
    int value;
};

#endif

A.cpp

#include "A.h"
#include "B.h"

int A::getBValue(){
    return b->value;
}

关于c++ - 类定义交叉引用时如何声明友元方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772688/

相关文章:

c++ - 在 map 上打印 vector

c++ - 如何防止 object=constructor(); C++中的赋值

c++ - 是否有必要在 friend 功能中使用访问器?

c++ - 具有模板参数enable_if的C++ friend 功能

C++模板类,模板成员友元函数匹配规则

c++ - boost::bind 和类成员函数

c++ - 不一致的 clock_gettime 性能

c++ - 是否可以有一个只能通过 ADL 找到的非友元函数?

c++ - c++中的 friend 保护方法

c++ - 我可以从 vector 的开头 move 对象吗?为什么不?