第2周项目--初见对象程序阅读

/*  
 * Copyright (c) 2015, 烟台大学计算机学院  
 * All rights reserved.  
 * 文件名称:test.cpp  
 * 作    者:姜甜甜 
 * 完成日期:2015年 3 月 17日  
 * 版 本 号:v1.0  
 *  
 * 问题描述:阅读第二个面向对象的程序--同样功能的程序提倡以下面的形式书写(这是专业人士更愿意使用的方式),阅读程序,回答相关问题;
 * 输入描述: NULL;
 * 程序输出: NULL。
#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;
}

思考:

  • 概括这种写法的特点。类内的函数在类外定义
  • 在类定义中,公共成员在前,私有成员在后,有何好处?___私有成员无法访问,也没必要关注,将公共成员放前面更清晰。
  • 成员函数的实现写在类定义之外,有何好处?________便于阅读
  • 将第5public: 去掉,记录出现的问题______,原因是_____。加上public,将程序改回正确状态。
  • main.cpp|14|error: 'void Student::set_data(int, char*, char)' is private|
  • main.cpp|20|error: 'void Student::display()' is private|
  • 成员函数变为程序默认的私有。
  • 将第18void Student::display( )写作为void display( ),即去掉Student::,结果会是_____Student::的作用是表示该函数属于。将程序改回正确状态。
  • main.cpp|22|error: 'num' was not declared in this scope|
  • main.cpp|23|error: 'name' was not declared in this scope|
  • main.cpp|24|error: 'sex' was not declared in this scope|
  • 在第30行后加一句:stud1.num=3,记录出现的情况,并解释原因。______num为私有,不能直接引用
  • main.cpp|10|error: 'int Student::num' is private|
  • 去掉刚加的那一行,将第31stud1.display();中的stud1.去掉,记录出现的情况,并解释原因。_display是类内的成员函数,使用需说明
  • main.cpp|31|error: 'display' was not declared in this scope|
  • 在32行后增加cout<<sizeof(stud1)语句,看输出的结果,请做出解释___
  • 输出了28  将stud1的属性所占字节输出:4+20+1=25,
  • 字节对齐,(可减少指令周期)
  • 初学者常将类定义后的分号丢掉,试将13行最后的分号去掉,记录出现的提示,并做出解释。_________
  • 你能想到的其他“坏”点子继续折腾吗?折腾出真知!




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值