C++ 构造函数

在本教程中,我们将通过帮助示例了解 C++ 构造函数及其类型。

构造函数是一种特殊类型的成员函数,在创建对象时会自动调用。

在 C++ 中,构造函数与类同名,并且没有返回类型。例如,

class Wall {
  public:
    // create a constructor
    Wall() {
      // code
    }
};

在这里,函数 Wall()Wall 类的构造函数。构造函数的特点:

  • 与类同名,
  • 没有返回类型
  • public

C++ 默认构造函数

没有参数的构造函数称为默认构造函数。在上面的例子中, Wall() 是一个默认构造函数。

示例 1:C++ 默认构造函数

此 C++ 程序演示了默认构造函数的用法。

#include <iostream>
using namespace std;

// declare a class
class  Wall {
  private:
    double length;

  public:
    // default constructor to initialize variable
    Wall() {
      length = 5.5;
      cout << "Creating a wall." << endl;
      cout << "Length = " << length << endl;
    }
};

int main() {
  Wall wall1;
  return 0;
}

输出

Creating a wall.
Length = 5.5

在这里,当 wall1 对象被创建时, Wall() 构造函数被调用。在构造函数中设置了对象的变量 length5.5

注意: 如果我们没有在我们的类中定义构造函数,那么 C++编译器会自动创建一个空的且没有参数的默认构造函数。

C++ 参数化构造函数

在 C++ 中,带参数的构造函数称为参数化构造函数。这是初始化成员数据的首选方法。

示例 2:C++ 参数化构造函数

本 C++ 程序计算了墙的面积。

#include <iostream>
using namespace std;

// declare a class
class Wall {
  private:
    double length;
    double height;

  public:
    // parameterized constructor to initialize variables
    Wall(double len, double hgt) {
      length = len;
      height = hgt;
    }

    double calculateArea() {
      return length * height;
    }
};

int main() {
  // create object and initialize data members
  Wall wall1(10.5, 8.6);
  Wall wall2(8.5, 6.3);

  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}

输出

Area of Wall 1: 90.3
Area of Wall 2: 53.55

在这里,我们创建了一个参数化构造函数 Wall() ,它有 2 个参数: double lendouble hgt 。这些参数中包含的值用于初始化成员变量 lengthheight.

当我们创建 Wall 类的对象时,我们将成员变量的值作为参数传递。代码如下:

Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);

成员变量如此初始化后,我们现在可以使用 calculateArea() 函数计算墙的面积。

C++ 复制构造函数

C++ 中的复制构造函数用于将一个对象的数据复制到另一个对象。

示例 3:C++ 复制构造函数

#include <iostream>
using namespace std;

// declare a class
class Wall {
  private:
    double length;
    double height;

  public:

    // 参数化构造函数
    Wall(double len, double hgt) {
      length = len;
      height = hgt;
    }

    // 复制构造函数
    Wall(Wall &obj) {
      length = obj.length;
      height = obj.height;
    }

    double calculateArea() {
      return length * height;
    }
};

int main() {
  // create an object of Wall class
  Wall wall1(10.5, 8.6);

  // copy contents of wall1 to wall2
  Wall wall2 = wall1;

  // print areas of wall1 and wall2
  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}

输出

Area of Wall 1: 90.3
Area of Wall 2: 90.3

在这个程序中,我们使用了复制构造函数将 Wall 类的一个对象的内容复制到另一个对象。复制构造函数的代码是:

Wall(Wall &obj) {
  length = obj.length;
  height = obj.height;
}

请注意,此构造函数的参数持有 Wall 类的对象的地址。

在 中 main() ,我们然后创建两个对象 wall1wall2 然后拷贝 wall1 的内容到 wall2

// 拷贝 `wall1` 的内容到 `wall2`
Wall wall2 = wall1;

在这里, wall2 对象通过传递 wall1 对象的地址作为参数来调用它的复制构造函数,即 &obj = &wall1

注意: 构造函数主要用于初始化对象。它们还用于在创建对象时运行默认代码。