两人类交好

Two Classes Befriending Each Other

我正在尝试让两个 class 成为朋友,但我一直收到 "Use of Undefined type A" 错误消息。

这是我的代码:

我尝试添加 class 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;
}

我正在尝试通过好友 class A 访问 class B,反之亦然。

正如@user888379 所指出的,在完全声明 类 之后移动 showAshowB 方法的实现将解决您的问题。以下是工作代码:

#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 以获得更详细的分析。

您无法访问 myFriendA.aVariable,因为编译器不知道它的存在。它只知道 class A 存在(因为第二行的前向声明),但它还没有完全定义,所以它不知道它的 members/methods 是什么。

如果你想让它工作,showA() 必须在 class 范围之外声明。

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