文档详情

c++程序设计实验辅导及习题解答-实验11.docx

发布:2017-12-07约3.8千字共12页下载文档
文本预览下载声明
实 验 十 一任务1:程序调试。类静态数据的应用。下列程序设计了一个职工类,职工类中包括职工姓名、薪水和所有职工的薪水总和allSalary。薪水总和员是所有职工对象薪水的统计和,它属于类而不属于某个对象,因而设置为static数据。 程序为:#include stdafx.h#include iostreamusing namespace std;#include string.h class Employee{ private: char name[30]; float salary; static float allSalary; public: Employee(char *n, float s){ strcpy(name, n); salary = s; allSalary = allSalary + salary;}~Employee(void){}static float GetAllSalary(void){ return allSalary; }};float Employee::allSalary = 0;void main(void){Employee e1(张三, 4500);Employee e2(王五, 5200);Employee e3(李四, 2450);float all;all = Employee::GetAllSalary( );cout AllSalary = all endl;}任务2:程序设计。应用类静态数据实现类名对象间的数据访问。参照任务1,定义一个类,描述某人的姓名和具有的现金数量,此某人有4个子女A、B、C、D,当初父亲具有现金10000元,每年提供给这4个子女的钱分别为1000、500、2000、1800元。当四个子女访问一次后,父亲还剩多少现金?设计代码运行如下:#include stdafx.h#include iostreamusing namespace std;#include string.h class people{ private: char name[30]; float salary; static float allSalary; public: people(char *n, float s){ strcpy(name, n); salary = s; allSalary = allSalary - salary;}~people(void){}static float GetAllSalary(void){ return allSalary; }};float people::allSalary = 10000;void main(void){people e1(A, 1000);people e2(B, 500);people e3(C, 2000); people e4(D, 1800);float all;all = people::GetAllSalary( ); cout 访问一次后还剩现金为: all endl;}任务3:程序调试。用友元函数计算两点间的距离。#include stdafx.h#include iostreamusing namespace std;#include math.hclass Point{public : Point(double xx ,double yy) {x=xx ; y=yy;} void Getxy() ; friend double Distance(Point a,Point b); private: double x,y;} ;void Point::Getxy() { cout(x ,y)endl; }double Distance(Point a , Point b){ double dx= a.x - b.x ; double dy= a.y - b.y ; return sqrt (dx*dx+dy*dy );}void main(){ Point p1(3.0,4.0),p2(6.0,8.0) ; p1.Getxy(); p2.Getxy(); double d=Distance(p1,p2); coutDistance is dendl;}调试上述程序,回答以下问题:函数Distance是否可以定义在类外?答:不能,友元函数一定要定义在类内。是否可以用对象调用函数Distance?答:不可以,友元函数是直接调用的。任务4:程序设计有一个向量类Vector,包括一个点的坐标位置x和y,设计两个友元函数,实现两个向量的加法和减法运算。程序设计如下:#includeiostream.h#include math.hclass vector{p
显示全部
相似文档