
C++项目 使用多文件,用两个cpp文件运行报错,而用标准的两个cpp和一个h头文件就能成功,是什么问题?
//主函数lab015.cpp#include<iostream>#include"lab014.h"usingnamespacestd;intmain(){Xtestx...
//主函数lab015.cpp
#include <iostream>
#include "lab014.h"
using namespace std;
int main()
{
X testx1;
Y testy1;
Z testz1;
testy1.g(testx1);
cout<<testx1.Geti()<<endl;
testz1.f(testx1);
cout<<testx1.Geti()<<endl;
testz1.h(testx1);
cout<<testx1.Geti()<<endl;
system("Pause");
}
//lab014.cpp
#include <iostream>
using namespace std;
class X;
class Y
{
public:
void g(X &x1);
};
class X
{
public:
X();
X(int num);
int Geti();
friend class Z;
friend void Y::g(X &x1);//其他类的成员函数作为友元函数的函数声明
private:
int i;
};
class Z
{
public :
void f(X &x1);
void h(X &x1);
};
X::X()
{
i = 0;
}
X::X(int num)
{
i = num;
}
int X::Geti()
{
return i;
}
void Y::g(X &x1)
{
x1.i+=1;
}
void Z::f(X &x1)
{
x1.i+=5;
}
void Z::h(X &x1)
{
x1.i+=10;
}
//学C++的时候做的一个题,在主函数里面包含了lab014.cpp,里面实现类的定义和实现
//如果没有#include lab014.cpp,会报错说没有关于类的定义
//如果不包含lab014.cpp,又会报错说有重复的函数定义
//但如果把类定义放在一个h文件里,把类实现放在cpp文件中,就能运行成功 展开
#include <iostream>
#include "lab014.h"
using namespace std;
int main()
{
X testx1;
Y testy1;
Z testz1;
testy1.g(testx1);
cout<<testx1.Geti()<<endl;
testz1.f(testx1);
cout<<testx1.Geti()<<endl;
testz1.h(testx1);
cout<<testx1.Geti()<<endl;
system("Pause");
}
//lab014.cpp
#include <iostream>
using namespace std;
class X;
class Y
{
public:
void g(X &x1);
};
class X
{
public:
X();
X(int num);
int Geti();
friend class Z;
friend void Y::g(X &x1);//其他类的成员函数作为友元函数的函数声明
private:
int i;
};
class Z
{
public :
void f(X &x1);
void h(X &x1);
};
X::X()
{
i = 0;
}
X::X(int num)
{
i = num;
}
int X::Geti()
{
return i;
}
void Y::g(X &x1)
{
x1.i+=1;
}
void Z::f(X &x1)
{
x1.i+=5;
}
void Z::h(X &x1)
{
x1.i+=10;
}
//学C++的时候做的一个题,在主函数里面包含了lab014.cpp,里面实现类的定义和实现
//如果没有#include lab014.cpp,会报错说没有关于类的定义
//如果不包含lab014.cpp,又会报错说有重复的函数定义
//但如果把类定义放在一个h文件里,把类实现放在cpp文件中,就能运行成功 展开
2个回答
展开全部
厄,本来就该如此啊,.h文件是做定义的,cpp是源文件。。
#include 指令是用来包含头文件的
#include 指令是用来包含头文件的
更多追问追答
追问
但我在看#include 这个指令的时候,书上说可以包含cpp文件又是怎么回事呢?
追答
我看了一下编译器,原来不分.h .cpp 包含文件与后缀无关。。
GCC如此,不知道你用哪个编译器。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询