简体   繁体   English

从同一类中的另一个构造函数调用一个构造函数

[英]calling one constructor from another in same class

1) First Code 1) 第一个代码

class A
{
public:
    int i;
    int b;
    A(int temp){
        i=temp;
        A();
        b=0;
    }

    A(){
        b=0;
    }

    void display(){
        printf("%d %d\n",i,b);//1 0
    }
};

int  main(){
    A Aobj(1);
    Aobj.display();
    return 0;
}

Output: 1 0输出:1 0

2) Second Code 2) 第二个代码

class A
{
public:
    int i;
    int b;
    A(int temp) : i(temp), A(), b(0) {}//Error
    A() : b(0) {}
    void display(){
        printf("%d %d\n",b,i);
    }
};

int  main()
{
    A Aobj(1);
    Aobj.display();
    return 0;
}

I was expecting that both the codes will show same behavior and will produce an error as calling one constructor from the other in the same class is not permitted.我期望这两个代码将显示相同的行为,并且会产生错误,因为不允许从同一类中的另一个构造函数调用一个构造函数。 It's not C++11.这不是 C++11。

So why does using the intializer list make a difference?那么为什么使用初始化列表会有所不同呢? I compiled this codes in g++ 4.3.4 .我在 g++ 4.3.4 中编译了这些代码。

A(); is not doing what you think it does.不是在做你认为它会做的事情。

Replace it with double();double();替换它double(); or char();char(); or any other type.或任何其他类型。 Note that it works.请注意,它有效。

All you are doing is creating an anonymous additional instance of the type then throwing it away.您所做的就是创建该类型的匿名附加实例,然后将其丢弃。 It has no impact on this and will not do what you think it does.它有没有影响this和你想象的那样是不行的。

The initializer list works in C++11 the way you would expect.初始值设定项列表在 C++11 中以您期望的方式工作。

This has nothing to do with C++11 at all.这与 C++11 完全没有关系。

As pointed out by Yakk in the first case, you construct an anonymous member non recursively through a different constructor (the default constructor).正如 Yakk 在第一种情况下所指出的,您可以通过不同的构造函数(默认构造函数)非递归地构造一个匿名成员。

In case 'B';在“B”的情况下; you try to initialize from the initialzier list a member that doesn't exist.您尝试从初始列表中初始化一个不存在的成员。 You don't have an instance of A or an A* existing within A to initialize.你不必实例AA*中存在A初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM