完全掌握C++编程中构造函数使用的超级学习教程

2020-01-06 14:26:49王冬梅

如果声明了任何非默认构造函数,编译器不会提供默认构造函数:


class Box {
  Box(int width, int length, int height) 
    : m_width(width), m_length(length), m_height(height){}
};
private:
  int m_width;
  int m_length;
  int m_height;

};

int main(){

  Box box1(1, 2, 3);
  Box box2{ 2, 3, 4 };
  Box box4;   // compiler error C2512: no appropriate default constructor available
}

如果类没有默认构造函数,将无法通过单独使用方括号语法来构造该类的对象数组。例如,在前面提到的代码块中,框的数组无法进行如下声明:


Box boxes[3];  // compiler error C2512: no appropriate default constructor available

但是,你可以使用初始值设定项列表将框的数组初始化:


Box boxes[3]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

复制和移动构造函数
复制构造函数是特殊成员函数,它采用对相同类型对象的引用作为输入,并创建它的副本。移动也是特殊成员函数构造函数,它将现有对象的所有权移交给新变量,而不复制原始数据。

显式默认构造函数和已删除构造函数
你可以显式设置默认复制构造函数、设置默认构造函数、移动构造函数、复制赋值运算符、移动赋值运算符和析构函数。你可以显式删除所有特殊成员函数。 
派生类中的构造函数
派生类构造函数始终调用基类构造函数,因此,在完成任何额外任务之前,它可以依赖于完全构造的基类。调用基类构造函数进行派生,例如,如果 ClassA 派生自 ClassB,ClassB 派生自 ClassC,那么首先调用 ClassC 构造函数,然后调用 ClassB 构造函数,最后调用 ClassA 构造函数。
如果基类没有默认构造函数,则必须在派生类构造函数中提供基类构造函数参数:


class Box {
public:
  Box(int width, int length, int height){
    m_width = width;
    m_length = length;
    m_height = height;
  }

private:
  int m_width;
  int m_length;
  int m_height;
};

class StorageBox : public Box {
public:
  StorageBox(int width, int length, int height, const string label&) : Box(width, length, height){
    m_label = label;
  }
private:
  string m_label;
};

int main(){

  const string aLabel = "aLabel";
  StorageBox sb(1, 2, 3, aLabel);
} 

具有多重继承的类的构造函数
如果类从多个基类派生,那么将按照派生类声明中列出的顺序调用基类构造函数:


#include <iostream>
using namespace std;

class BaseClass1 {
public:
  BaseClass1() {
    cout << "BaseClass1 constructor." << endl;
  }
};
class BaseClass2 {
public:
  BaseClass2() {
    cout << "BaseClass2 constructor." << endl;
  }
};
class BaseClass3{
public:
  BaseClass3() {
    cout << "BaseClass3 constructor." << endl;
  }
};
class DerivedClass : public BaseClass1, public BaseClass2, public BaseClass3 {
public:
  DerivedClass() {
    cout << "DerivedClass constructor." << endl;
  }
};

int main() {
  DerivedClass dc;
}