文档详情

实验6-静态成员和友元.doc

发布:2017-07-18约5.2千字共14页下载文档
文本预览下载声明
内蒙古科技大学信息工程学院计算机系 《面向对象程序设计》实验报告 姓名 张国强 学号 1667159127 班级 软件一班 实验日期 第 15 周(星期 三 ) 6 月 7 日第一 节 项目号、实验名称 实验6 静态成员和友元 实 验 要 求 (任课 教 师 提 供) 一、实验目的 1.理解静态成员(静态数据成员、静态成员函数)的作用与使用; 2.理解友元(友元函数、友元类)的作用于使用。 二、实验内容 2.1练习(一): 1.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。 #include iostream.h #include string.h class CStudent { public: CStudent(char *n, int a); ~CStudent(); static void SetAge(int age); private: char *name; int age; static int nTotalObj; }; int CStudent::nTotalObj = 0; CStudent::CStudent(char *n, int a) :age(a) { int nLen = strlen(n); name = new char[nLen+1]; strcpy(name,n); name[nLen] = \0; nTotalObj++; } CStudent::~CStudent() { delete[] name; nTotalObj--; } void CStudent::SetAge(int age) { this-age = age; } void main() { CStudent stu1(张三,25); CStudent str2(李四,26); coutCStudent::nTotalObj=CStudent::nTotalObjendl; } 问题一:以上程序编译能通过吗,为什么? 问题二:成员变量nTotalObj在程序中起什么作用,它是如何实现的? 问题三:如果规定该程序的主函数和类CStudent中的成员变量的属性不允许改变,应该如何改正该程序? 2.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。 #include iostream.h #include string.h class CStudent { public: CStudent(char *n, int a); ~CStudent(); private: char *name; int age; }; CStudent::CStudent(char *n, int a) :age(a) { int nLen = strlen(n); name = new char[nLen+1]; strcpy(name,n); name[nLen] = \0; } CStudent::~CStudent() { delete[] name; } class CTeacher { public: CTeacher(char *tn, int ta); ~CTeacher(); void SetStuAge(int a); private: char *name; int age; CStudent stu; }; CTeacher::CTeacher(char *tn, int ta) :age(ta) { int nLen = strlen(tn); name = new char[nLen+1]; strcpy(name,tn); name[nLen] = \0; } CTeacher::~CTeacher() { delete[] name; } void CTeacher::SetStuAge(int a) { stu.age = a; } void main() { CStudent stu(张三,25); CTeacher tea(李四,26); } 问题一:以上程序有两大错误,试指出来,并改正之? 2.2练习(二): 1.某商店经销一种货物。货物成箱购进,成箱卖出,购进和卖出时以重量为单位,各箱的重量不一样,因此,商店需要记录下货物库存的总重量。试用C++模拟商店货物购进和卖出的情况。(提示:将总重量定义为静态成员) 实 验 内 容 (由学 生 填 写) 实验一 第一个错误的地方 错误的地方见上图,将静态成员声明为私有的就不能在类外直接访问,要想访问只能在定义一个静态的共有的成员函数来访问。 第二个错误的地方
显示全部
相似文档