问题描述
我想定义两个类,A和B.A有一个数据成员,该成员是B类对象,并且在类中进行了初始化. A也有一种方法来检索此B类型数据成员中的值,并且该方法将在B中声明为好友方法.这是我的代码:
I want to define two classes, A and B. A has a data member which is a Class B object and is in-class initialised. A also has a method to retrieve the value in this B type data member and this method would be declared as a friend method in B. Here is my code:
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之间的交叉引用问题的方法?
And unsurprisingly the compilation had failed because of unknown type B in class A definition. I had tried to swap the definitions of A and B in the source and the result was even worse. Is there a possible way to resolve this cross reference issue between A and B?
推荐答案
如果这是您所拥有的完整代码,则问题在于编译器当时不知道B
是什么编译类A
.解决此问题的一种方法是创建指向B的指针,而不是拥有B本身:
If this is the complete code as you have it, then the problem is that the compiler doesn't know what a B
is at the time it is compiling class A
. One way to solve it is by creating a pointer to B instead of having a B itself:
A.h
#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;
}
这篇关于类定义交叉引用时如何声明朋友方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!