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