第2周 阅读程序-初识对象(一)

来源:互联网 发布:ubuntu 精简版 编辑:程序博客网 时间:2024/06/01 07:30

(1)阅读第一个面向对象的程序,程序结构是所有成员函数都在类内定义,阅读程序,回答相关问题(请写在博客中,程序及问题在BB平台中提供)

#include <iostream>#include <cstring>using namespace std;class Student{private:    int num;    char name[20];    char sex;public:    void set_data(int n, char *p ,char s)    {        num=n;        strcpy(name,p);        sex=s;    }    void display()    {        cout<<"num: "<<num<<'\n';        cout<<"name "<<name <<'\n';        cout<<"sex "<<sex<<'\n';    }};int main(){    Student stud1,stud2;    stud1.set_data(1,"He",'f');    stud2.set_data(2,"She",'m');    stud1.display();    stud2.display();    return 0;}

问题:

 

 

  • 程序中定义的类名是________?

  • Student

  • 在main函数中,定义的stud1和stud2称为____________?

  • 对象

  • 该类中,num、name、sex称为类的_________,其访问权限为________,意味着_________。

  • 属性 私有 该成员只能被本类中的成员函数引用,类外不能被调用。

  • 该类中,set_data和display称为类的_______,其访问权限为________,意味着_________。

  • 成员函数 公有 该成员可以被本类中的成员函数所引用,也可以被类外调用。

  • 在main()函数中26行后,调用stud1.display();,将会出现什么结果?请解释原因。________

  • 运行窗口会随机数出三个字符或数字,因为没有对类的属性进行赋值,计算机将随机赋值。

  • 请删除上面加的一行代码,在main()函数的28行后,调用stud2.sex='f';,记录提示的错误_____?为什么会这样?_______

  • 9:10: error: 'char Student::sex' is private

  • 29:11: error: within this context

  • 因为sex是类内私有数据,不能在类外被调用。

  • 将第9行char sex;移到第10行后面,即将sex成员声明为公共数据成员,再次编译程序。请解释不会出错的原因,并对这种做法进行评价。________________________

  • 不会出错的原因是sex由私有数据变为公有数据,可在类外被调用。这样做会将数据库的数据更改,最好不要。

  • 将第6行private: 去掉,结果是否发生变化,请解释原因。_______

  • 不会发生变化 class中成员默认为private

  • 将第10行public: 去掉,记录出现的情况,并解释原因。_______

  •       11:10: error: 'void Student::set_data(int, char*, char)' is private

          27:30: error: within this context

          27:30: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

          11:10: error: 'void Student::set_data(int, char*, char)' is private

          28:31: error: within this context

          28:31: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

  •       17:10: error: 'void Student::display()' is private

  •       29:19: error: within this context

  •       17:10: error: 'void Student::display()' is private

  •       30:19: error: within this context

  • 原因是公用成员变成私有成员,在类外无法获得权限完成成员函数的调用。

 


 

 

 

 

 

 

 

0 0
原创粉丝点击