实验4 类中数据的共享与保护
一、实验目的与实验要求
(1)掌握友元的定义和应用。
(2)掌握对象数组的定义、初始化方法及应用。 (3)掌握指针和引用作为函数参数的应用。
(4)掌握在类内定义静态数据成员以实现共享的基本方法,并根据需要定义相应的静态成员函数专门操作静态数据成员。
(5)掌握类中常数据成员的定义及初始化方法,正确使用常数据成员。
(6)理解常成员函数的意义以及常对象的意义,在程序中正确定义常对象,并正确调用相应的成员函数。
二、实验内容
1. 编写一个程序,定义一个Circle类,按下述内容要求定义相关的数据成员及成员函数,最后在主函数中输出各圆的半径及对应面积,并一次性输出平均面积。
①Circle类中定义4个数据成员:常数据成员PI代表圆周率,静态数据成员count用于统计圆对象的个数,普通的double型数据成员r代表圆的半径,普通的double型数据成员area代表圆的面积,所有数据成员均定义为私有属性。再定义相关的成员函数,用于求单个圆的面积、输出圆的半径及面积、获取静态数据成员的值。
② 主函数中以一维对象数组定义若干个圆类的对象,调用相应的函数,求面积,并输出每个圆的半径及对应的面积,并且输出一次圆的个数。
③ 在Circle类中增加一个友元函数的声明,用来求所有圆面积的平均值,并实现该函数的代码,主函数中增加调用此函数的语句,输出所有圆面积的平均值。
#include
const double PI; static int count; double Radius; public:
Circle(double r):PI(3.14)
{ }
//Radius=new sizeof (r); Radius=r; count++;
double Area();
double Circumference(); int Getmount(); Circle():PI(3.14) {} };
double Circle::Area() {
return PI*Radius*Radius; }
double Circle::Circumference() {
return Radius; }
int Circle::Getmount() {
return count; }
int Circle::count=0; int main()
{
// Circle c1(3),c2(4); // cout<<\
of
c1=\
c1=\
// cout<<\
of
c2=\
c2=\
double r;
Circle c[2]={Circle(3),Circle(4)};
//int count=0;
for(int i=0;i<2;i++) {
//
// cin>>r; Circle(r);
//c[i].Circle::Area();
//
//Circle Area();
//Ciecle Circumference();
//Circle c1;
cout<<\
of
c=\
c=\
}
of
of
of
return 0; }
2. 程序改错,请修改下列程序,尽量减少增行或减行,使程序的运行结果如下:
The number of all students: 0 The number of all students: 1 The number of all students: 0 The number of all students: 2 The number of all students: 2
要求:类中的数据成员连同访问属性均不可以修改。
//错误程序源代码如下:
#include
using namespace std; class Student { private:
char name[20];
static int total; //用来统计学生总人数
public: };
static int Student::total=0; Student::Student(char *p=\{ }
static int Student::GetTotal( ) { }
int main() {
cout<<\Student *p=new Student(\cout<<\delete p; return total; strcpy(name,p); total++;
Student( ) { total++; } ~Student( ) { } Student(char *p=\static int GetTotal( );
cout<<\ }
#include
Student s[2];
cout<<\cout<<\return 0;
搜索“diyifanwen.net”或“第一范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,第一范文网,提供最新人文社科实验4 类中数据的共享与保护 全文阅读和word下载服务。
相关推荐: