Line类,建立工程,使用多文件的组织结构实现程序

请改写课本例题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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值