【问题标题】:Two Classes Befriending Each Other两个班级互相友好
【发布时间】:2019-06-12 18:21:12
【问题描述】:

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

【问题讨论】:

  • 您可能想尝试在声明 A 之后移动 B 方法的实现。

标签: c++ friend-class


【解决方案1】:

您无法访问 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;
}

【讨论】:

    【解决方案2】:

    正如@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了解更详细的分析。

    【讨论】:

      猜你喜欢
      • 2012-12-31
      • 2018-01-16
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多