构造函数可以像 函数重载 一样被重载。
重载的构造函数具有相同的名称(类名),但参数的数量不同。根据传递的参数的数量和类型,会调用相应的构造函数。
示例 1:构造函数重载
// C++ program to demonstrate constructor overloading
#include <iostream>
using namespace std;
class Person {
private:
int age;
public:
// 1. Constructor with no arguments
Person() {
age = 20;
}
// 2. Constructor with an argument
Person(int a) {
age = a;
}
int getAge() {
return age;
}
};
int main() {
Person person1, person2(45);
cout << "Person1 Age = " << person1.getAge() << endl;
cout << "Person2 Age = " << person2.getAge() << endl;
return 0;
}
输出
Person1 Age = 20 Person2 Age = 45
在此程序中,我们创建了一个名为 Person
的类,该类有一个变量 age。
我们还定义了两个构造函数 Person()
和 Person(int a)
。
- 当创建对象 person1 时,会调用第一个构造函数,因为我们没有传递任何参数。此构造函数将 age 初始化为
20
。 - 当创建 person2 时,由于传递了
45
作为参数,会调用第二个构造函数。此构造函数将 age 初始化为45
。
函数 getAge()
返回 age 的值,我们使用它来打印 person1 和 person2 的 age。
示例 2:构造函数重载
// C++ program to demonstrate constructor overloading
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
public:
// 1. Constructor with no arguments
Room() {
length = 6.9;
breadth = 4.2;
}
// 2. Constructor with two arguments
Room(double l, double b) {
length = l;
breadth = b;
}
// 3. Constructor with one argument
Room(double len) {
length = len;
breadth = 7.2;
}
double calculateArea() {
return length * breadth;
}
};
int main() {
Room room1, room2(8.2, 6.6), room3(8.2);
cout << "When no argument is passed: " << endl;
cout << "Area of room = " << room1.calculateArea() << endl;
cout << "\nWhen (8.2, 6.6) is passed." << endl;
cout << "Area of room = " << room2.calculateArea() << endl;
cout << "\nWhen breadth is fixed to 7.2 and (8.2) is passed:" << endl;
cout << "Area of room = " << room3.calculateArea() << endl;
return 0;
}
输出
When no argument is passed: Area of room = 28.98 When (8.2, 6.6) is passed. Area of room = 54.12 When breadth is fixed to 7.2 and (8.2) is passed: Area of room = 59.04
- 当创建 room1 时,会调用第一个构造函数。 length 被初始化为
6.9
,breadth 被初始化为4.2
。 - 当创建 room2 时,会调用第二个构造函数。我们传递了参数
8.2
和6.6
。length 被初始化为第一个参数8.2
,breadth 被初始化为6.6
。 - 当创建 room3 时,会调用第三个构造函数。我们传递了一个参数
8.2
。length 被初始化为参数8.2
。breadth 默认初始化为7.2
。
推荐教程:C++ 函数重载。