C++上机实验(2)

2019-08-01 22:38

{

size = sz;

ia = new int[size]; if (array != NULL) { for (int ix = 0; ix < size; ++ix) ia[ix] = ix + 1; } else { for (int ix = 0; ix < size; ++ix) ia[ix] = 0; } }

int main() {

int a[10] = { 1,2,3,4,5,6,7,8,9,10 };

IntArray arr1(10), arr2(a, 5), arr3(arr2); arr1.printAll(); arr2.printAll(); arr3.printAll(); return 0; }

4.设有一个点myPoint类的定义如下: class myPoint { public:

myPoint(double x0=0.0,double y0=0.0):x(x0),y(y0) {} myPoint(myPoint &np):x(np.x),y(np.y) {} double GetX() { return x;} double GetY() {return y;} void SetX(double x0) {x=x0;} void SetY(double y0) {x=y0;}

void SetPoint(double x0,double y0) {x=x0;y=y0;} void SetPoint(myPoint &np) { x=np.x; y=np.y;} double GetLength(myPoint p) {

return sqrt((x-p.x)*(x-p.x) +(y-p.y)*(y-p.y)); }

void Printit() { cout<<\private:

double x ,y; };

试定义一个三角形Triangle类,在Triangle类中以点myPoint类的3个对象p1、p2、p3作为数据成员,表示三角形的三个顶点。Triangle类具有计算三角形的周长和面积的功能。请编写程序上机调试并运行。:

实验代码:

#include using namespace std; class myPoint { public:

myPoint(double x0 = 0.0, double y0 = 0.0) :x(x0), y(y0) {} myPoint(myPoint &np) :x(np.x), y(np.y) {} double GetX() { return x; } double GetY() { return y; }

void SetX(double x0) { x = x0; } void SetY(double y0) { x = y0; }

void SetPoint(double x0, double y0) { x = x0; y = y0; } void SetPoint(myPoint &np) { x = np.x; y = np.y; } double GetLength(myPoint p) {

return sqrt((x - p.x)*(x - p.x) + (y - p.y)*(y - p.y)); }

void Printit() { cout << \ << x << \ << y << \; } private:

double x, y; } ;

class Triangle { public: //面积

double Area(double a, double b, double c) { double p; p = (a + b + c) / 2; return sqrt(p*(p - a)*(p - b)*(p - c)); }

//周长

double Perimeter(double a, double b, double c) { return a + b + c; }

myPoint p1,p2, p3; };

int main() {

Triangle tri;

tri.p1.SetPoint(1, 1); tri.p2.SetPoint(3, 0); tri.p3.SetPoint(2, 3);

cout << \三角形的顶点为:\; tri.p1.Printit(); tri.p2.Printit(); tri.p3.Printit(); cout << endl;

cout << \三角形的面积为:\ << tri.Area(tri.p1.GetLength(tri.p2), tri.p2.GetLength(tri.p3), tri.p1.GetLength(tri.p3)) << endl;

cout << \三角形的周长为: \ << tri.Perimeter(tri.p1.GetLength(tri.p2), tri.p2.GetLength(tri.p3), tri.p1.GetLength(tri.p3)) << endl; return 0; }

三、实验使用环境

Windows 10 VS2017

四、实验小结

1)了解了对接口编程的思想,学会了将类的定义放在头文件中,函数的实现应放在.cpp文件中,将类成员函数的实现和类的使用放在不同的cpp文件中的编程模式,也学会了用预编译条件指令来限制头文件内容的引入,避免头文件内容被重复引入的方法。

2)学会了先构造类再实例化对象的编程思想,初步理解了面向对象的概念,深入了解了构造函数和析构函数的特点。

3)深入了解了构造函数和析构函数的特点。 4)学会了将重复代码抽出,简化代码的方法。

5)学会了将一个类作为另一个类的数据成员时的初始化,函数调用。


C++上机实验(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:浙江省杭州市2018年中考语文模拟命题比赛试卷

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: