c++ include问题

来源:百度知道 编辑:UC知道 时间:2024/05/24 08:49:27
项目文件:main.cpp,c1.cpp而h1.h与前二文件同于项目文件夹而未加入项目
----------------------------------------
main.cpp
#include "h1.h"
int main(){
s s1;//编译未通过
return 0;
}
----------------------------------------
h1.h
#ifndef _H_1_
#define _H_1_
class s;
#endif
----------------------------------------
c1.cpp
#include "h1.h"
class s{
public:
s() { x = 1; }
private:
int x;
};
----------------------------------------
问,出错了,信息 \main.cpp
[waring] in function in main()
's' undeclared(first use this function)
(Each undeclared identifier is reported only once for each
parse ereor before ';' token
dev 4.9 ,这也有关系吗?

与编译器没有关系。这是因为你没有把类的实现方式没有放到h1.h文件中,main.cpp文件中只有类的声明,在main()函数要用到类,这时编译器只有类的声明,但它不知道类的实现在那里,从而就不知道类有哪些内容,类的对象占用多大的空间,也就只有报错了。你应该这样放置文件的内容,这也是大家所使用的方式
----------------------------------------
main.cpp
#include "h1.h"
int main(){
s s1;//编译未通过
return 0;
}
----------------------------------------
c1.cpp //这个文件放的是类的函数实现
#include "h1.h"

int s::func1()
{
}
int s::func2()
{
}
----------------------------------------
h1.h //这个文件放的是类的实现
#ifndef _H_1_
#define _H_1_
class s{
public:
s() { x = 1; }
int func1();//类的其他函数
int func2();//类的其他函数
private:
int x;
};
#endif
----------------------------------------
还有最好为这个类起个有意义的名字,类的头文件名和cpp文件名最好相同

这个看你是用的什么编译器。。。用的vc还是devc