C++中的构造函数重载

C++ 中,我们可以在同名的类中拥有多个构造函数,只要每个构造函数具有不同的参数列表即可。这个概念称为构造函数重载,与函数重载非常相似。

  • 重载的构造函数本质上具有相同的名称(类的确切名称),但参数的数量和类型不同。
  • 根据传递的参数的数量和类型调用构造函数。
  • 在创建对象时,必须传递参数以让编译器知道需要调用哪个构造函数。
// C++ program to illustrate
// Constructor overloading
#include <iostream>
using namespace std;

class construct
{

public:
	float area;
	
	// Constructor with no parameters
	construct()
	{
		area = 0;
	}
	
	// Constructor with two parameters
	construct(int a, int b)
	{
		area = a * b;
	}
	
	void disp()
	{
		cout<< area<< endl;
	}
};

int main()
{
	// Constructor Overloading
	// with two different constructors
	// of class name
	construct o;
	construct o2( 10, 20);
	
	o.disp();
	o2.disp();
	return 1;
}

输出:

0 
200
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖果Autosar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值