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

构造函数:处理对象的初始化,是一种特殊的成员函数,与其他函数不同,不需要用户来调用它,在建立对象时自动执行。

注意:(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个数据成员的值为1530,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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值