C ++中的构造方法重载

众所周知,函数重载是面向对象语言的核心功能之一。我们可以使用相同的功能名称;其参数集不同。在这里,我们将看到如何重载C ++类的构造函数。构造函数重载有几个重要概念。

  • 重载的构造函数必须具有相同的名称和不同数量的参数

  • 根据传递的参数的数量和类型来调用构造函数。

  • 我们在创建对象时必须传递参数,否则构造函数将无法理解将调用哪个构造函数。

示例

#include <iostream>
using namespace std;

class Rect{
   private:
   int area;
   public:
   Rect(){
      area = 0;
   }
   Rect(int a, int b){
      area = a * b;
   }
   void display(){
      cout << "The area is: " << area << endl;
   }
};

main(){
   Rect r1;
   Rect r2(2, 6);
   r1.display();
   r2.display();
}

输出结果

The area is: 0
The area is: 12