您的位置:首页 > 其它

第一周阅读程序(1) 成员函数在类内声明,类外定义

2015-03-18 08:48 302 查看
问题及代码

#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: 去掉,记录出现的问题__提示错误:原public内的函数为私有;原因是_类函数未定义的话默认为私有;加上public,将程序改回正确状态。
将第18行void Student::display( )写作为void display( ),即去掉Student::,结果会是__

F:\新建文件夹\初学对象\main.cpp|23|error: 'num' was not declared in this scope|

F:\新建文件夹\初学对象\main.cpp|24|error: 'name' was not declared in this scope|

F:\新建文件夹\初学对象\main.cpp|25|error: 'sex' was not declared in this scope|

Student::的作用是_引入到类内____。将程序改回正确状态。
在第30行后加一句:stud1.num=3,记录出现的情况:提示错误:num为私有。并解释原因。_私有成员不能在类外被直接调用;
去掉刚加的那一行,将第31行stud1.display();中的stud1.去掉,记录出现的情况: F:\新建文件夹\初学对象\main.cpp|11|error:
'int Student::num' is private|

F:\新建文件夹\初学对象\main.cpp|31|error: within this context|

并解释原因。私有成员不能在类外被直接调用;
在32行后增加cout<<sizeof(stud1)语句,看输出的结果

,请做出解释___?
初学者常将类定义后的分号丢掉,试将13行最后的分号去掉,记录出现的提示:F:\新建文件夹\初学对象\main.cpp|14|error: expected ';' after class definition|

并做出解释。_少分号________
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐