构造函数不是用()调用,而是用{}调用?

时间:2019-02-17 05:01:11

标签: c++ constructor

所以我做了一些声明CLASS(OTHERCLASS());,它根本没有调用构造函数。我将()更改为{},然后调用所有构造步骤。为什么?

这是测试代码

#include <iostream>
using namespace std;
int g = 0;
struct A    {
    A() {
        cout << "A C" << endl;
        g++;
    }
    ~A() { cout << "A D" << endl; }
    int a = 0;
};

struct AA {
    AA(const A& a) {
        cout << "AA C" << endl;
        g++;
    }
    ~AA() { cout << "AA D" << endl; }
    int aa = 0;
};
struct AAA
{
    AAA(const AA& a) {
        cout << "AAA C" << endl;
        g++;
    }
    ~AAA() { cout << "AAA D" << endl; }
    int aaa = 0;
};


int main() {

    cout << g << endl;
    {
            AAA{AA{A{}}};     // <=== constructors get call
    //  AAA(AA(A()));      //<<=======this one didn't invoke any constructors
    // AAA aaa=AAA(AA(A()));    //<=== this one invoked constructors
    }
    cout << g << endl;
    getchar();
    return 0;
}

使用AAA(AA(A()))的输出是

0
0

使用AAA{AA{A{}}}AAA aaa=AAA(AA(A()))输出为

0
A C
AA C
AAA C
AAA D
AA D
A D
3

一个AAA(AA(A()))有什么问题?

0 个答案:

没有答案