C++程序设计 第九章笔记

例9.2(1)
如果第七行写了private,程序就无法运行,因为private的数据成员在主函数中无法通过"time1.hour"这种方式调用

#include<iostream>
using namespace std;
class Time
{
public:
    Time(int,int,int);//声明带参数的构造函数
*第七行private:*
    int hour;
    int minute;
    int second;
};
Time::Time(int h,int m,int s)//定义带参数的构造函数
{
    hour=h;
    minute=m;
    second=s;
}
int main()
{
    Time time1(12,23,34);//建立对象,指定成员的值
    cout<<time1.hour<<":"<<time1.minute<<":"<<time1.second;
    return 0;
}

例9.2(2)
若想用private,就要再定义一个用来输出private的数据成员的函数

#include<iostream>
using namespace std;
class Time
{
public:
    Time(int,int,int);//声明带参数的构造函数
    void show();
private:
    int hour;
    int minute;
    int second;
};
Time::Time(int h,int m,int s)//定义带参数的构造函数
{
    hour=h;
    minute=m;
    second=s;
}
int main()
{
    Time time1(12,23,34);//建立对象,指定成员的值
    time1.show();//引用公共函数show
    return 0;
}
void Time::show()
{
    cout<<hour<<":"<<minute<<":"<<second;
}

例9.2(3)
用参数初始化表对数据成员初始化

#include<iostream>
using namespace std;
class Time
{
public:
    Time(int h,int m,int s):hour(h),minute(m),second(s){}//声明带参数的构造函数
    void show();
private:
    int hour;
    int minute;
    int second;
};
int main()
{
    Time time1(12,23,34);//建立对象,指定成员的值
    time1.show();//引用公共函数show
    return 0;
}
void Time::show()
{
    cout<<hour<<":"<<minute<<":"<<second;
}

但如果某一数据成员是数组(例name),则应在构造函数的函数体中对其赋值,如下:

class student
{
public:
   Student(int n,char s,char nam[]):num(n),sex(s)
      {
          strcpy(name,nam);
      } 
private:
   int num;
   char sex;
   char name[20]
};

定义对象:

Student stu(2018,'m',"wang li")

例9.3
构造函数的重载
一个类中可以定义多个构造函数,以便为对象提供不同的初始化方法

#include<iostream>
using namespace std;
class Time
{
public:
    Time();//声明一个无参的构造函数
    Time(int h,int m,int s):hour(h),minute(m),second(s){}//声明带参数的构造函数
    void show();
private:
    int hour;
    int minute;
    int second;
};
int main()
{
    Time time1(12,23,34);//建立对象,指定实参
    time1.show();//引用公共函数show
    Time time2;//建立对象,不指定实参
    time2.show();
    return 0;
}
Time::Time()
{
    hour=10;
    minute=10;
    second=10;
}
void Time::show()
{
    cout<<hour<<":"<<minute<<":"<<second<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值