0
点赞
收藏
分享

微信扫一扫

C++中的构造函数重载

骑在牛背上看书 2022-02-05 阅读 42

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
 
举报

相关推荐

0 条评论