3

我试图让两个班级彼此成为朋友,但我不断收到“使用未定义类型 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 类,反之亦然。

4

2 回答 2

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;
}

阅读此答案以获得更详细的分析。

于 2019-06-12T18:37:53.233 回答
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;
}
于 2019-06-12T18:39:16.357 回答