您的位置:首页 > 其它

构造函数的定义和构造函数的重载

2016-05-29 13:42 169 查看
构造函数:处理对象的初始化,是一种特殊的成员函数,与其他函数不同,不需要用户来调用它,在建立对象时自动执行。
注意:(1)每建立一个对象,就调用一次构造函数;
(2)构造函数没有返回值,因此也没有类型,作用只是对对象进行初始化;
(3)构造函数不需要被用户调用,也不能被用户调用。
构造函数的重载:构造函数具有相同的名字,而参数的个数或参数类型不相同。
例1 编写一个基于对象的程序,在类中用带参数的构造函数对数据成员初始化,求长方柱的体积。
解:程序:
#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);
cout << "The volume of box1 is:" << box1.volume() << endl;
Box box2(15, 30, 21);
cout << "The volume of box2 is:" << box2.volume() << endl;
system("pause");
return 0;
}
结果:
The volume of box1 is:9000
The volume of box2 is:9450
请按任意键继续. . .
例2 定义两个构造函数,其中一个有参数,一个无参数,求长方柱的体积。
解:建立对象box1时,没有给出参数,系统找到与之对应的无参构造函数Box,执行此构造函数的结果是使3个数据成员的值均为10,然后输出box1的体积;建立对象box2时,给出3个实参,系统找到有3个形参的构造函数Box,执行此构造函数的结果是使3个数据成员的值为15,30,25,然后输出box2的体积。
程序:
#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()//在类外定义无参构造函数Box
{
height = 10;
width = 10;
length = 10;
}
int Box::volume()
{
return(height*width*length);
}
int main()
{
Box box1;
cout <<"The volume of box1 is:"<<box1.volume()<<endl;
Box box2(15,30,25);
cout << "The volume of box2 is:" << box2.volume() << endl;
system("pause");
return 0;
}
结果:
The volume of box1 is:1000
The volume of box2 is:11250
请按任意键继续. . .

本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1754910
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: