*copyright (c) 2014, 烟台大学计算机学院.
*All rights reserved.
*文件名称:test.cpp
*作者:陆云杰
*完成日期:2015年3月13日
*版本号:v1.0
*
*
*问题描述:阅读程序
*程序输入: 无
*程序输出: 无
*/
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
void set_data(int n, char *p,char s);
void display( );
private:
int num;
char name[20];
char sex;
};
void Student::set_data(int n, char *p,char s)
{
num=n;
strcpy(name,p);
sex=s;
}
void Student::display( )
{
cout<<"num: "<<num<<endl;
cout<<"name: " <<name<<endl;
cout<<"sex: " <<sex<<endl;
}
int main()
{
Student stud1,stud2;
stud1.set_data(1,"He",'f');
stud2.set_data(2,"She",'m');
stud1.display();
stud2.display();
return 0;
}
问题:
- 概括这种写法的特点____对成员函数先声明后定义____。
- 在类定义中,公共成员在前,私有成员在后,有何好处?_这样可以让用户将注意力集中在能被外界调用的成员上,使阅读者的思路更加清晰。__
- 成员函数的实现写在类定义之外,有何好处?____不但可以减少类体的长度,使类清晰,便于阅读,而且能使类的接口和类的实现细节分离,用户只能看到函数原型,而看不到函数的执行的细节,隐藏了函数的执行细节,会提高软件工程的质量。____
- 将第5行public: 去掉,记录出现的问题__
D:\C++\di2zhou\(2)\main.cpp|20|error: 'void Student::display()' is private|
D:\C++\di2zhou\(2)\main.cpp|31|error: within this context|
D:\C++\di2zhou\(2)\main.cpp|20|error: 'void Student::display()' is private|
___,原因是__去掉public后,系统默认成员函数为私有的,所以不能再类外被调用,会出现错误。___加上public,将程序改回正确状态。 - 将第18行void Student::display( )写作为void display( ),即去掉Student::,结果会是__||=== Build: Debug in (2) (compiler: GNU GCC Compiler) ===|
D:\C++\di2zhou\(2)\main.cpp||In function 'void display()':|
D:\C++\di2zhou\(2)\main.cpp|22|error: 'num' was not declared in this scope|
D:\C++\di2zhou\(2)\main.cpp|23|error: 'name' was not declared in this scope|
D:\C++\di2zhou\(2)\main.cpp|24|error: 'sex' was not declared in this scope|
___?Student::的作用是__限定display()函数是该类中的函数___。将程序改回正确状态。 - 在第30行后加一句:stud1.num=3,记录出现的情况,并解释原因。___||=== Build: Debug in (2) (compiler: GNU GCC Compiler) ===|
D:\C++\di2zhou\(2)\main.cpp||In function 'int main()':
D:\C++\di2zhou\(2)\main.cpp|10|error: 'int Student::num' is private___ - 因为num是私有的成员,不能再类外被调用。
- 去掉刚加的那一行,将第31行stud1.display();中的stud1.去掉,记录出现的情况,并解释原因_
D:\C++\di2zhou\(2)\main.cpp|31|error: 'display' was not declared in this scope,disply没有被定义,要使用类内的成员函数,必须加”stud1.“因为"stud1"是类的对象。
____ - 在32行后增加cout<<sizeof(stud1)语句,看输出的结果,请做出解释_多输出了“28”,这是stud1中的属性“num,sex,name”的占的字节的长度。__?
- 初学者常将类定义后的分号丢掉,试将13行最后的分号去掉,记录出现的提示,并做出解释:
D:\C++\di2zhou\(2)\main.cpp|13|error: expected ';' after class definition - 类的定义是一个独立的句子,所以结束后腰加分号。
- (3)在阅读上面两个程序的基础上再次深入体会下面的基本概念
- 声明一个类,可以定义出结构相同的一组对象——类是对象的抽象,对象是类的实例;
- 类/对象中包括数据成员和成员函数两部分——类/对象实现了对程序设计中要描述的实体的封装处理:将有关的数据和操作代码封装在一个对象中,形成一个基本单位,各个对象(如程序中stud1和stud2)之间相对独立,互不干扰。
- 信息隐蔽(imformation hiding)——将对象中某些部分(通过private限定符)对外隐蔽,即隐蔽其内部细节,只留下少量接口,以便与外界联系,接收外界的消息。
- 封装和信息隐蔽的优点:把对象的一部分属性和功能对外界屏蔽,从外界是看不到的,甚至是不可知的,有利于数据安全,防止无关的人了解和修改数据。同时,大大降低了操作对象的复杂程度。
-