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

C++ 使用多个构造函数调用初始化成员变量,c++,constructor,initialization,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

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

 #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;
}
#包括
使用名称空间std;
ABC班{
私人:
int x,y;
公众:
ABC(){

cout您可以在
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;
   }
};
ABC类
{
私人:
int x,y;
公众:
ABC():ABC(2,3)
{
std::cout
ABC(2,3);
不调用构造函数初始化成员,它只创建一个临时变量,该变量将立即销毁

如果你的意思是你应该:

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

cout
ABC(2,3);
创建
ABC
的本地临时实例。可能重复@πάνταῥεῖ 那么,我应该如何对同一个对象进行更改呢?另请参见。@Ashish-如果委托构造函数不可用,则必须按旧方法执行:
ABC():x(2),y(3){}
我无法在我使用的IDE上编译此代码块(Visual Studio 2010 Professional).>错误1错误C2614:“ABC”:非法成员初始化:“ABC”不是基或member@Ashish这仅适用于当前的c++11标准。VS2010太旧了。
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;
    }
};