我正试图使两个类彼此成为朋友,但我不断收到“使用未定义的A型使用”错误消息。
这是我的代码:
我试图添加A类;如顶部所示,但仍然相同。
#include <iostream>
class A;
class B
{
private:
int bVariable;
public:
B() :bVariable(9){}
void showA(A &myFriendA)
{
std::cout << "A.aVariable: " << myFriendA.aVariable << std::endl;// Since B is friend of A, it can access private members of A
}
friend class A;
};
class A
{
private:
int aVariable;
public:
A() :aVariable(7){}
void showB(B &myFriendB){
std::cout << "B.bVariable: " << myFriendB.bVariable << std::endl;
}
friend class B; // Friend Class
};
int main() {
A a;
B b;
b.showA(a);
a.showB(b);
system("pause");
return 0;
}
我正试图通过友谊使A类进入B类,反之亦然。
答案 0 :(得分:3)
正如@ user888379所指出的,在两个类都被完全声明之后移动showA
和showB
方法的实现将解决您的问题。以下是工作代码:
#include <iostream>
class A;
class B
{
private:
int bVariable;
public:
B() :bVariable(9){}
void showA(A &myFriendA);
friend class A; // Friend Class
};
class A
{
private:
int aVariable;
public:
A() :aVariable(7){}
void showB(B &myFriendB);
friend class B; // Friend Class
};
void B::showA(A &myFriendA) {
std::cout << "A.aVariable: " << myFriendA.aVariable << std::endl; // Since B is friend of A, it can access private members of A
}
void A::showB(B &myFriendB) {
std::cout << "B.bVariable: " << myFriendB.bVariable << std::endl; // Since A is friend of B, it can access private members of B
}
int main() {
A a;
B b;
b.showA(a);
a.showB(b);
return 0;
}
阅读this answer以获得更详细的分析。
答案 1 :(得分:3)
您无法访问myFriendA.aVariable,因为编译器不知道它存在。它所知道的只是一个类A存在(由于第二行中的正向声明),但是尚未完全定义,因此不知道其成员/方法是什么。
如果您想完成这项工作,必须在类范围之外声明showA()。
class A;
class B
{
private:
int bVariable;
public:
B() :bVariable(9){}
void showA(A &myFriendA);
friend class A;
};
class A
{
private:
int aVariable;
public:
A() :aVariable(7){}
void showB(B &myFriendB){
std::cout << "B.bVariable: " << myFriendB.bVariable << std::endl;
}
friend class B; // Friend Class
};
// Define showA() here
void B::showA(A &myFriendA)
{
std::cout << "A.aVariable: " << myFriendA.aVariable << std::endl;
}
int main() {
A a;
B b;
b.showA(a);
a.showB(b);
system("pause");
return 0;
}