C++ 构造函数重载

构造函数可以像 函数重载 一样被重载。

重载的构造函数具有相同的名称(类名),但参数的数量不同。根据传递的参数的数量和类型,会调用相应的构造函数。


示例 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 的值,我们使用它来打印 person1person2age


示例 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.9breadth 被初始化为 4.2
  • 当创建 room2 时,会调用第二个构造函数。我们传递了参数 8.26.6length 被初始化为第一个参数 8.2breadth 被初始化为 6.6
  • 当创建 room3 时,会调用第三个构造函数。我们传递了一个参数 8.2length 被初始化为参数 8.2breadth 默认初始化为 7.2

推荐教程C++ 函数重载

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战