使用好友函数时,不完整类型错误
incomplete type error , when using friend functions
#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();
}
相关文章:
- 类没有命名C++代码中的类型错误
- 不完整类型错误(E0409、E0070、E0515)
- 使用具有结构不完整类型错误的模板
- 不命名构造函数和析构函数上的类型错误
- 返回派生类型时出现协变类型错误
- 为什么此构造函数没有给出不完整的类型错误?
- 定义模板化结构的特征时出现不完整的类型错误
- 使用重载构造函数时出现不完整的类型错误
- 为什么我得到表达式必须有类类型错误?
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 枚举成员不是类型错误
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 外部 "C" Visual Studio 2015 中的显式类型错误,DLL 测试代码
- 非默认析构函数会导致不完整的类型错误
- 为什么按引用传入会导致绑定引用类型错误
- Objective-C C++ 包装器 类型错误的不完整定义
- 输入类型错误
- 当构造函数的参数类型错误时引发异常
- 命名空间中的'bad_cast' 'std' 未命名类型错误
- C UNWORKOWN类型错误