实验6静态成员函数与友元.docVIP

  • 35
  • 0
  • 约2.59千字
  • 约 5页
  • 2016-10-05 发布于重庆
  • 举报
实验6静态成员函数与友元

宁夏师范学院数学与计算机科学学院 《》实验报告 实验序号:          实验项目名称:学  号 姓  名 专业班 实验地点 指导教师 时间 一、实验目的及要求 4、学习友元函数和友元类的组合使用方法。 二、实验设备(环境)及要求 硬件:PC(PII以上,128M以上内存)、因特网接入; 软件:Windows XP操作系统、Office2003、。2学时 其他要求:验证题目和设计题目尽量完成;任选一个设计题目写实验报告 三、实验内容与步骤 分析:静态成员函数是类的一部分而不是对象的一部分。如果在类外调用公用的静态成员函数,要用类名和域运算符“::”而在本源代码中说明了静态成员函数引用非静态数据成员的方法,但是在C++中要习惯:只用静态成员函数引用静态数据成员,而不引用非静态数据成员。 9.12 分析:display是一个在类外定义的且未用类Time作限定的函数,它是非成员函数,不属于任何类。但由于声名了display是Time类的frieng函数,所以display函数可以引用Time中的私有成员 9.13 分析:feiend函数不仅可以是一般函数,而且可以使另一个类中的成员函数。 【设计题目】 1.设计并测试一个矩形类(Rectangle),属性为矩形的左下与右上角的坐标,矩形水平放置。操作为计算矩形周长与面积。类对象的数据由友元函数来进行访问。并对比友元函数、成员函数和普通函数使用上的不同。参考程序如下: //lab6_1.Cpp 实验源代码 #include iostream #include cmath using namespace std; class Rectangle { public: Rectangle(int t=0, int l=0, int d=0, int r=0) { top=t; left=l; down=d; right=r; } ~Rectangle() {}; friend void cal(Rectangle r); //定义友元函数 private: int top,left,down,right; }; void cal(Rectangle r) { cout矩形的周长是:2*(fabs(r.top-r.down)+fabs(r.left-r.right))endl; cout矩形的面积是:(fabs(r.top-r.down))*(fabs(r.left-r.right))endl; } int main() { Rectangle r1(100,200,600,400); cal(r1); return 0; } 2.定义Boat与Car两个类,二者都有weight属性,定义它们的一个友元函数totalWeight(),计算二者的重量和。 参考程序如下: //lab6_2.cpp 实验源代码: #include iostream #include cmath using namespace std; class Boat { public: Boat(double w) { weight=w; } friend double totalWeight(Boat a) {return a.weight;} private: double weight; }; class Car { public: Car(double w) {weight=w; } friend double totalWeight(Car b) {return b.weight;} private: double weight; }; void main() { Boat aa(254); Car bb(395); couttotalweight:totalWeight(aa)+totalWeight(bb)endl; } 3.课后运行教材习题9-9,体会静态数据成员和成员函数的含义。 实验源代码: #include iostream using namespace std; class Product { public: Product(int n,int q,float p):num(n),quantity(q),price(p){} void total(); static float average(); static void display(); private: int num; int quantity; float price; static float discoun

文档评论(0)

1亿VIP精品文档

相关文档