基本概念

  • 成员函数的一种

    • 名字与类名一样,可传参,没有返回值(void)也不行
    • 作用是对对象进行初始化,如给成员变量赋值
    • 如没有,编译器会自动生成一个无参的默认构造函数
      1. class Complex {
      2. private:
      3. double real, image;
      4. public:
      5. Complex(double r, double i = 0);
      6. };
      7. Complex a; // error
      8. Complex *pa = new(3, 4) // ok
  • 数组调用

    1. class Test {
    2. public:
    3. Test(int n); // (1)
    4. Test(int n, int m); // (2)
    5. Test(); // (3)
    6. };
    7. Test arr1[3] = {1, Test(1,2)}; // 分别用(1)(2)(3)初始化
    8. Test * pArr[3] = {new Test(4), new Test(1,2) }; // 只生成了两个对象,调用两次构造函数