C++程序的多文件组成 如何将一个源程序分成三个文件 最好举例说明 我不明白为什么我分成后出现
发布网友
发布时间:2022-04-27 07:46
我来回答
共2个回答
热心网友
时间:2023-10-06 00:52
把一个源程序分成三个文件,一般情况包含《文件名》.h头文件用于实现函数的声明,函数文件<文件名>.cpp,主函数文件头文件和函数文件用#include“文件名.h(.cpp)开头声明!
下边例子头文件head.h是类定义头文件,head.cpp是类实现文件4-4.cpp是主函数文件
//head.h
class Point{
public:
Point(int xx=0,int yy=0){
x=xx;
y=yy;
}
Point(Point &p);
int getX(){return x;}
int getY(){return y;}
private:
int x,y;
};class Line{
public:
Line(Point xp1,Point xp2);
Line(Line &l);
double getLen(){return len;}
private:
Point p1,p2;
double len;
};
//head.app
#include"head.h"
#include<iostream>
#include<cmath>
using namespace std;
Point::Point(Point &p){
x=p.x;
y=p.y;
cout<<"Calling the copy constructor of Point"<<endl;
}
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
cout<<"Calling consturctor of Line"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}
Line::Line (Line &l):p1(l.p1),p2(l.p2){
cout<<"Calling the copy constructor of Line"<<endl;
len=l.len ;
}
//4_4.app
#include "head.h"
#include <iostream>
using namespace std;
int main(){
Point myp1(1,1),myp2(4,5);
Line line(myp1,myp2);
Line line2(line);
cout<<"The length of the line2 is:";
cout<<line.getLen()<<endl;
cout<<"The length of the line2 is:";
cout<<line2.getLen()<<endl;
return 0;
}
综合到一块如下:
#include <iostream>
using namespace std;
class Point{
public:
Point(int xx=0,int yy=0){
x=xx;
y=yy;
}
Point(Point &p);
int getX(){return x;}
int getY(){return y;}
private:
int x,y;
};class Line{
public:
Line(Point xp1,Point xp2);
Line(Line &l);
double getLen(){return len;}
private:
Point p1,p2;
double len;
};using namespace std;
Point::Point(Point &p){
x=p.x;
y=p.y;
cout<<"Calling the copy constructor of Point"<<endl;
}
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
cout<<"Calling consturctor of Line"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}
Line::Line (Line &l):p1(l.p1),p2(l.p2){
cout<<"Calling the copy constructor of Line"<<endl;
len=l.len ;
}
int main(){
Point myp1(1,1),myp2(4,5);
Line line(myp1,myp2);
Line line2(line);
cout<<"The length of the line2 is:";
cout<<line.getLen()<<endl;
cout<<"The length of the line2 is:";
cout<<line2.getLen()<<endl;
return 0;
}追问分成三个文件
#include "head.h"在程序里找不到
我是不明白分开的情况
追答新建head.h文件,你建了吗?
热心网友
时间:2023-10-06 00:52
你用什么开发工具,如果VC的话把student,h文件放在项目文件夹下,如果是其他工具,把头文件放在include搜索路径里面就行了