错误:聚合“第一个”具有不完整的类型,无法定义。

12

我已经编写了这个头文件 (header1.h):

#ifndef HEADER1_H
#define HEADER1_H

class first ;

//int summ(int a , int b) ;



#endif

还有这些源文件(header1.cpp 和 main.cpp):

#include <iostream>
#include "header1.h"

using namespace std;


class first
{
    public:
  int a,b,c;
  int sum(int a , int b);

};

  int first::sum(int a , int b)
{

    return a+b;
}

 

#include <iostream>
#include "header1.h"


using namespace std;


   first one;

int main()
{
   int j=one.sum(2,4);
    cout <<  j<< endl;
    return 0;
}

但是当我在CodeBlocks中运行此程序时,我遇到了以下错误:

聚合体“第一个”具有不完整的类型,不能定义。


1
对于其他人来说,这个错误可能有另一个原因;请包含所需的头文件。 - SAMPro
3个回答

16

您不能在 .cpp 文件中放置类声明。必须将其放在 .h 文件中,否则编译器将看不到它。当 main.cpp 被编译时,类型 "first" 是 class first;。这根本没有任何用处,因为这不告诉编译器任何信息(例如 first 的大小或该类型上有效的操作)。请将此部分移至:

class first
{
public:
    int a,b,c;
    int sum(int a , int b);
};

将头文件 header1.cpp 中的内容移植到 header1.h 文件中,并删除 header1.h 中的 class first; 声明。


1
如果您也使用了主函数,只需在顶部定义类并稍后定义主函数即可。不必显式创建单独的头文件。

1
你需要在头文件中声明整个类(该头文件被实际使用该类的任何地方包含)。否则,编译器将不知道如何在类中“查找”sum(或应为该类保留多少空间)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接