练习
网易云学习歌单链接: 点我听歌.
数据结构与算法推荐链接(JAVA语言): link.
1、定义构造成员函数处理输入输出。
在类Time中定义了构造函数Time,它与所在的类同名。在建立对象时自动执行构造函数,
该函数的作用是为对象中的各个数据成员赋初值 0。 注意只有执行构造函数时才为数据
成员赋初值。
程序运行时首先建立对象t1,并对t1中的数据成员赋初值0,然后执行t1.set_time函数,
从键盘输入新值给对象t1的数据成员,再输出t1的数据成员的值。接着建立对象t2,同时
对t2中的数据成员赋初值0,最后输出t2的数据成员的初值。
代码:
#include <iostream>
using namespace std;
class Time
{
public:
Time()
{
hour=0;
minute=0;
sec=0;
}
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
int main()
{
Time t1;
t1.set_time();
t1.show_time();
Time t2;
t2.show_time();
return 0;
}
void Time::set_time()
{
cin>>hour;
cin>>minute;
cin>>sec;
}
void Time::show_time()
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
亦可以在类外定义构造函数
Time::Time()
{
hour=0;
minute=0;
sec=0;
}
运行结果:
2.有两个长方柱,其长、宽、高分别为:
(1)12,25,30
(2)15,30,21
编写程序,在类中用带参数的构造函数,计算它们的体积。
分析:可以在类中定义一个计算长方体体积的成员函数计算对象的体积。
代码:
#include <iostream>
using namespace std;
class Box
{
public:
Box(int,int,int);
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h,int w,int len) // 长方体构造函数
{
height=h;
width=w;
length=len;
}
int Box::volume() // 计算长方体的体积
{
return(height*width*length);
}
int main()
{
Box box1(12,25,30); // 定义对象box1
cout<< " box1体积=" << box1.volume() <<endl;
Box box2(15,30,21); // 定义对象box2
cout<< " box2体积= " << box2.volume()<<endl;
return 0;
}
构造函数Box有3个参数,分别代表长、宽、高。在主函数中定义对象box1时,指定了实参12,25,30。然后调用成员函数计算长方体的体积。
提醒:
(1)带形参的构造函数在定义对象时必须指定实参
(2)用这种方法可以实现不同对象的初始化。
运行结果:
3、在题2的基础上定义两个构造函数其中一个无参数,另一个有参数。
代码:
#include <iostream>
using namespace std;
class Box
{
public:
Box(int,int,int);
Box();
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h,int w,int len) // 长方体构造函数
{
height=h;
width=w;
length=len;
}
Box::Box();
int Box::volume() // 计算长方体的体积
{
return(height*width*length);
}
int main()
{
Box box1(12,25,30); // 定义对象box1
cout<< " box1体积=" << box1.volume() <<endl;
Box box2(15,30,21); // 定义对象box2
cout<< " box2体积= " << box2.volume()<<endl;
return 0;
}
运行结果:
4、将题3中的构造函数改用带默认值的参数,长、宽、高的默认值都是10
代码:
#include <iostream>
using namespace std;
class Box
{
public:
Box();
int volume();
private:
int height;
int width;
int length;
};
Box::Box() // 长方体构造函数
{
height=10;
width=10;
length=10;
}
int Box::volume() // 计算长方体的体积
{
return(height*width*length);
}
int main()
{
Box box1; // 定义对象box1
cout<< " box1体积=" << box1.volume() <<endl;
Box box2