2016-07-19 148 views
2

我想执行以下代码:有多个构造函数初始化成员变量调用

#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调用的参数化构造函数!
-858993460 -858993460

不应成员变量与值2和3被初始化?

+0

'ABC(2,3);'创建一个本地速度为'ABC'的实例。 –

+0

[为什么我应该更喜欢使用成员初始化列表?](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – LogicStuff

+0

@πάνταῥεῖ那么我应该如何在同一个对象上进行更改? – Ashish

回答

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

您在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; 
    } 
}; 
+0

我无法在IDE上编译此代码块我正在使用(Visual Studio 2010 Professional)。 >错误错误C2614:'ABC':非法成员初始化:'ABC'不是基础或成员 – Ashish

+1

@Ashish这仅适用于当前的C++ 11标准。 VS2010太旧了。 –

相关问题