一、构造函数的用法
#include <iostream>
using namespace std;
class Time
{
public:
Time()
{
hour= 0;
minute= 0;
sec= 0;
}
void set_time();
void show_time(void);
private:
int hour;
int minute;
int sec;
};
void Time::set_time(void)
{
cout << "分别请输入小时、分钟、秒数:" ;
cin >> hour;
cin >> minute;
cin >> sec;
}
void Time::show_time(void)
{
cout << "将输入的数字用标准时间显示为:" << endl;
cout << hour << ":" << minute << ":" << sec << endl;
}
int main()
{
Time t1;
t1.set_time();
t1.show_time();
return 0;
}
二、构造函数的重载
#include <iostream>
using namespace std;
class Box
{
public:
Box();
Box(int h, int w, int len):height(h), width(w), length(len){ }
int Volume();
private:
int height;
int width;
int length;
};
Box::Box()
{
height= 10;
width= 10;
length= 10;
}
int Box::Box::Volume()
{
return (height * width * length);
}
int main()
{
Box b1;
cout << "通过无参构造函数初始化的盒子体积为:" << b1.Volume() << endl;
Box b2;
cout << "通过有参构造函数初始化的盒子体积为:" << b2.Volume() << endl;
return 0;
}
三、析构函数
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
public:
Student(int n, string nam, char s)
{
num= n;
name= nam;
sex= s;
cout << "构造函数执行完毕!" << endl;
}
~Student()
{
cout << "析构函数已执行!" << endl;
}
void display();
private:
int num;
string name;
char sex;
};
void Student::display()
{
cout << "I am " << name << ", my Id is " << num;
if(sex=='f')
{
cout << " and I am a girl." << endl;
}
else
{
cout << "and I am a boy." << endl;
}
}
int main()
{
Student stu1(10001, "Hawk Chung", 'f');
stu1.display();
Student stu2(10002, "Zahuw", 'm');
stu2.display();
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)