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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17799906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:27:34  来源:igfitidea点击:

Error : aggregate 'first one' has incomplete type and cannot be defined

c++codeblocks

提问by ggcodes

I have written this header file (header1.h):

我写了这个头文件(header1.h)

#ifndef HEADER1_H
#define HEADER1_H

class first ;

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



#endif

and this source files (header1.cpp and main.cpp):

和这个源文件(header1.cpp and 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;
}

But when I run this program in codeblocks, I give this Error :

但是当我在中运行这个程序时codeblocks,我给出了这个错误:

aggregate 'first one' has incomplete type and cannot be defined .

聚合“第一个”的类型不完整,无法定义。

回答by Borgleader

You can't put the class declaration in the .cpp file. You have to put it in the .h file or else it's not visible to the compiler. When main.cpp is compiled the type "first" is class first;. That's not useful at all because this does not tell anything to the compiler (like what size first is or what operations are valid on this type). Move this chunk:

您不能将类声明放在 .cpp 文件中。你必须把它放在 .h 文件中,否则编译器看不到它。编译 main.cpp 时,类型“first”是class first;. 这根本没有用,因为这不会告诉编译器任何信息(例如首先是什么大小或对该类型有效的操作)。移动这个块:

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

from header1.cpp to header1.h and get rid of class first;in header1.h

从 header1.cpp 到 header1.h 并去掉class first;header1.h

回答by Arpan Adhikari

If you're using a main function as well, just define the class at the top and define the main later. It is not necessary to explicitly create a separate header file.

如果您也使用 main 函数,只需在顶部定义类,然后再定义 main。没有必要显式创建单独的头文件。

回答by Mats Petersson

You need to declare the whole class in a headerfile (that is included every place the class is actually used). Oterhwise, the compiler won't know how to "find" sumin the class (or how much space it should reserve for the class).

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