- 1、本文档共11页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
C第5次作业
实验五:数据的共享与保护
1. 定义一个Cat类,拥有静态数据成员HowManyCats,记录Cat的个体数目;静态成员函数GetHowMany(),存取HowManyCats。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。
(1) 实验分析:本题的难点就是(2) 程序代码:#include iostream
#include string
using namespace std;
class Cat
{
public:
Cat(string name=Untitle,double age=0,double weight=0):name(name),age(age),weight(weight){HowManyCats++;}
Cat(Cat c):name(c.name),age(c.age),weight(c.weight){}
static int GetHowMany();
void showCat();
private:
string name;
double age,weight;
static int HowManyCats;
};
int Cat::HowManyCats=0;
int Cat::GetHowMany()
{
return HowManyCats;
}
void Cat::showCat()
{
for(int i=0;i30;i++)
cout*;
coutendl;
coutThe name of this cat is: nameendl;
coutThe age of this cat is(years): ageendl;
coutThe weight of this cat is(kg): weightendl;
for(i=0;i30;i++)
cout*;
coutendl;
}
void outputwords();
int main()
{
outputwords();
coutNow we input data of one catendl;
Cat cat1;
cat1.showCat();
outputwords();
coutNow we input data of one catendl;
Cat cat2(Jack,8.5,80.7);
cat2.showCat();
outputwords();
coutNow we input data of one catendl;
Cat cat3(哈哈,-100,0.5);
cat3.showCat();
outputwords();
return 0;
}
void outputwords()
{
coutNow there are Cat::GetHowMany() catsendlendl;
}
(3) 实验结果:
2. 设计一个点(point)类,
1)在点类中设计友员函数,求两点间的距离。
2)设计一个线段(line)类。
(1)实验分析:两点间的距离用普通函数dist来计算。
(2)程序代码:#includeiostream
#includecmath
using namespace std;
class Point
{
public:
Point(int X=0,int Y=0)
{
x=X;
y=Y;
}
friend float dist(Point po1,Point po2);
private:
int x,y;
};
float dist(Point po1,Point po2)
{
double x=po1.x-po2.x;
double y=po1.y-po2.y;
return (sqrt(x*x+y*y));
}
class line
{
public:
line(Point px1,Point px2){po1=px1,po2=px2;}
float length(){return dist(po1,po2);}
private:
Point po1,po2;
};
void main()
{
int x,y;
cout请输入第一点的坐标:;
cinxy;
Point p1(x,y);
cout请输入第二点的坐标:;
cinxy;
Point p2(x,y);
line AB(p1,p2);
coutThe distance is AB.length()endl;
}
(3)实验结果:
3、定义一个学生类,数据成员有:总人数、姓名、性别、成绩等,设计程序要求能统
文档评论(0)