使用多个构造函数调用初始化成员变量

时间:2016-07-19 06:26:04

标签: c++ constructor initialization

我正在尝试执行以下代码:

 #include <iostream>
using namespace std;

class ABC {
private:
    int x, y;
public:
    ABC(){
        cout << "Default constructor called!" << endl;
        ABC(2, 3);
        cout << x << " " << y << endl;
    }
    ABC(int i, int j){
        cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl;
        x = i;
        y = j;
        cout << x << " " << y << endl;
    }
};

int main(){
    ABC a;
    return 0;
}

我得到以下输出:

  

默认构造函数!
  参数化构造函数调用参数2 3!
  2 3
  -858993460 -858993460

不应使用值2和3初始化成员变量吗?

2 个答案:

答案 0 :(得分:3)

ABC(2, 3);不会调用构造函数来初始化成员,它只是创建一个临时变量,它将立即被销毁。

如果您的意思是delegating constructor,您应该:

ABC() : ABC(2, 3) {
    cout << "Default constructor called!" << endl;
    cout << x << " " << y << endl;
}

请注意,这是一个C ++ 11功能。如果不能使用C ++ 11,则可以添加成员函数。

class ABC {
private:
    int x, y;
    init(int i, int j) {
        x = i;
        y = j;
    }
public:
    ABC(){
        cout << "Default constructor called!" << endl;
        init(2, 3);
        cout << x << " " << y << endl;
    }
    ABC(int i, int j){
        cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl;
        init(i, j);
        cout << x << " " << y << endl;
    }
};

答案 1 :(得分:1)

您在ABC()正文中创建临时变量。您可以使用此语法来克服此问题:

class ABC 
{
private:
   int x, y;
public:
   ABC() : ABC(2,3)
   {
       std::cout << "Default constructor called!" << std::endl;
   }
   ABC(int i, int j)
   {
       std::cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << std::endl;
       x = i;
       y = j;
       std::cout << x << " " << y << std::endl;
   }
};