例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;
}