问题
I have written this header file (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)
:
#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 :
aggregate 'first one' has incomplete type and cannot be defined .
回答1:
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:
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
回答2:
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.
回答3:
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" sum
in the class (or how much space it should reserve for the class).
来源:https://stackoverflow.com/questions/17799906/error-aggregate-first-one-has-incomplete-type-and-cannot-be-defined