使用好友函数时,不完整类型错误

incomplete type error , when using friend functions

本文关键字:类型 错误 好友 函数      更新时间:2023-10-16
#include <stdio.h>
class B;
class A;
class A
{
    int a;
    friend int B::f();
};

class B
{
    int b;
    class A x;
public:
    int f();
};
int B::f()
{
    // ...
}
main()
{
    class B b;
    b.f();
}

错误:

a.cpp:9: error: invalid use of incomplete type ‘struct B’
a.cpp:2: error: forward declaration of ‘struct B’

这个问题不能通过把B的定义放在A的前面来解决B有一个a类型的对象

对于本例,将B设置为友类就可以了,但是在在我的实际代码中,我在B中有更多的成员函数(所以我需要替代解决方案)。

最后,谁能给我一些链接来解释编译器是怎么做的

您不能按原样做您想做的事情。为了在类A中声明友元函数,需要在定义类A之前知道类B的性质。要使B类包含A类的实例,必须在B类定义之前知道A类的性质。第二十二条军规。

如果将B类设置为A类的友类,则

前者不适用。如果您修改B以包含指向A类实例的指针或引用,则后者不适用。

A之前定义B,并声明指向A的指针作为B的成员数据:

class A; //forward declaration
class B
{
    int b;
    A  *px; //one change here - make it pointer to A
 public:
    int f();
};
class A
{    
    int a;
    friend int B::f();
};

或者,可以使整个类B成为A的友类,这样就不必使成员数据指向A

class B; //forward declaration
class A
{    
    int a;
    friend class B;
};
class B
{
    int b;
    A   x; //No change here 
 public:
    int f();
};

正向声明类A;定义B类;定义A类;B:定义:f。

#include <cstdio>
class A;

class B
{
int b;
public:
int f();
};
class A
{
int a;
friend int B::f();
};

int B::f()
{
}
main() 
{
class B b;
b.f();
}