C++ 中的重载构造函数
 
本文将解释如何在 C++ 中实现重载构造函数。
C++ 中的构造函数基础和构造函数重载
构造函数是 C++ 类中的一个特殊成员函数,其任务是初始化类的对象。构造函数没有特殊名称,不能直接调用,但是每次创建给定的类时,通常都会调用相应的构造函数。虽然,我们声明了与类本身同名的构造函数。由于 C++ 提供了一种在给定范围内定义多个同名函数的方法,我们也可以为单个类定义多个构造函数。
请注意,函数重载规则适用于重载的构造函数,因为它们需要在接受的参数或类型的数量上有所不同。C++ 指定了不同类型的构造函数,它们通常有特定的用例,但由于其范围广泛,我们不会在本文中深入研究这些细节。
在以下示例代码中,定义了 Student 类,包括两个 string 类型的 private 数据成员。这些成员应该在创建 Student 类的新实例时初始化,但我们假设只有 name 成员是必需的。因此,我们需要有不同的方法来构造这个类的对象,其中之一只初始化 name 成员。
因此,我们定义了第一个构造函数,它只接受一个 string 参数并将相应的消息打印到控制台。后一步仅用于轻松识别构造函数的行为。此外,我们还定义了第二个构造函数,它接受两个 string 参数并初始化两个数据成员 - name 和 last_name。
#include <iostream>
using std::cout;
using std::endl;
using std::string;
class Student {
 private:
  string name;
  string last_name;
 public:
  explicit Student(string n) : name(std::move(n)) {
    cout << "Constructor 1 is called" << endl;
  };
  Student(string &n, string &ln) : name(n), last_name(ln) {
    cout << "Constructor 2 is called" << endl;
  };
  string getName() { return name; }
  string getLastName() { return last_name; }
};
int main() {
  string n1("James");
  string n2("Kale");
  Student s1(n1, n2);
  cout << s1.getName() << endl;
  cout << s1.getLastName() << endl;
  cout << "------------------" << endl;
  Student s2(n1);
  cout << s2.getName() << endl;
  cout << s2.getLastName() << endl;
  cout << "------------------" << endl;
  return EXIT_SUCCESS;
}
输出:
Constructor 2 is called
James
Kale
------------------
Constructor 1 is called
James
------------------
请注意,当我们在 main 程序中创建 s1 对象时,第二个构造函数被调用,因为我们提供了两个参数,当 s2 被初始化时,第一个构造函数被调用。在这种情况下,我们有两个具有不同数量参数的构造函数,但一般来说,我们可以定义两个具有相同数量参数但它们接受的类型不同的构造函数。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Jinku Hu
    
