请改写课本例题4-4线段(Line类),建立工程,使用多文件的组织结构实现程序。要求:
(1)文件划分:类定义文件(*.h),类实现文件(*.cpp),类使用文件(,cpp,主函数文件)。
(2)每个类的设计单独放在1个(.h)文件中,工程共包括5个文件。
(3)使用条件编译指令以免文件多次包含的情况。
(4)在Dev C++或VC中建立工程:文件-新建-项-(Basic—EmptyProject—C++项目)-新建文件夹Line,项目名称为Line,将所有文件保存在名为Line的文件夹中。VC建立过程是:文件—>新建—>工程—>Win32 Console Application。
实验思路:可以先在同一个.cpp文件里将代码实现,再按照题意分为五部分Point.h、Point.cpp、Line.h、Line.cpp、main.cpp,在头文件里记得加上条件编译指令以免文件多次包含的情况。
Point.h
#ifndef POINT_H
#define POINT_H
class Point{
public:
Point(int xx=0, int yy=0);
Point(Point &p);
~Point(){}
int getX()const;
int getY()const;
private:
int x, y;
};
#endif
Point.cpp
#include "Point.h"
#include <iostream>
using namespace std;
Point::Point(int xx, int yy):x(xx),y(yy){}
Point::Point(Point &p):x(p.x),y(p.y)
{
cout << "Calling the copy constructor of Point" << endl;
}
int Point::getX() const {return x;}
int Point::getY() const {return y;}
Line.h
#ifndef LINE_H
#define LINE_H
#include "Point.h"
class Line{
public:
Line(Point xp1, Point xp2);
Line(Line &l);
double getLen();
private:
Point p1,p2;
double len;
};
#endif
Line.cpp
#include "Point.h"
#include "Line.h"
#include <iostream>
#include <cmath>
using namespace std;
Line::Line(Point xp1, Point xp2): p1(xp1),p2(xp2)
{
cout << "Calling constructor 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;
}
double Line::getLen(){
return len;
}
main.cpp
#include "Point.h"
#include "Line.h"
#include <iostream>
using namespace std;
int main()
{
Point myp1(1,1),myp2(4,5); //建立Point类的对象
Line line(myp1,myp2); //建立Line类的对象
Line line2(line); //利用复制构造函数建立一个新对象
cout << "The length of the line is: ";
cout << line.getLen() << endl;
cout << "The length of the line2 is: ";
cout << line2.getLen() << endl;
return 0;
}