Solve Error: 'has incomplete type', foward declaration of 'class x'

简介:

在C++的OOB编程中,有时候我们会遇到这样的错误Error: 'has incomplete type',forward declaration of 'class x',那么是什么原因引起的这个问题呢,我们首先来看下面这段代码:

// Error: field '_a' has incomplete type 'A'
// forward declaration of 'class A'
class A;

class B {
public:
    B(A a): _a(a) {}
private:
    A _a;
};

class A {
public:
    A(B b): _b(b) {}
private:
    B _b;
};

在上面这段代码中,类A和类B互相含有对方作为自己的私有成员变量,那么不管谁写在前面,如果不事先声明另一个的话,都会报错找不到定义,那么我们事先声明A就没事了吗,也不是,像上面那样B中声明A的对象还是会出错,因为编译器不知道A的定义,无法生成类A的实例,所以会报错。一种改正方法是把对象实例变成对象指针,如下所示:

// Correct
class A;

class B {
public:
    B(A *a): _a(a) {}
private:
    A *_a;
};

class A {
public:
    A(B *b): _b(b) {}
private:
    B *_b;
};

本文转自博客园Grandyang的博客,原文链接: Solve Error: 'has incomplete type', foward declaration of 'class x',如需转载请自行联系原博主。

相关文章
【已解决】Error: Element type is invalid: expected a string (for built-in components) or a class/function
Error: Element type is invalid: expected a string (for built-in components) or a class/function
2340 0
【已解决】Error: Element type is invalid: expected a string (for built-in components) or a class/function
|
PyTorch 算法框架/工具 Python
RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future rel
RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future rel
93 0
|
C语言
error: implicit declaration of function ‘VerifyFixClassname‘ is invalid in C99 [-Werror,-Wimplicit-f
error: implicit declaration of function ‘VerifyFixClassname‘ is invalid in C99 [-Werror,-Wimplicit-f
117 0
error: implicit declaration of function ‘read‘ [-Werror,-Wimplicit-function-declaration]
error: implicit declaration of function ‘read‘ [-Werror,-Wimplicit-function-declaration]
180 0
解决办法:Type safety: The expression of type List needs unchecked conversion to conform
解决办法:Type safety: The expression of type List needs unchecked conversion to conform
194 0
|
计算机视觉
opencv出错:error: (-213:The function/feature is not implemented) Unknown/unsupported array type
opencv出错:error: (-213:The function/feature is not implemented) Unknown/unsupported array type
406 0