对象初始化

时间:2019-03-17 19:47:25

标签: c++

我已经看到以下代码段:test()函数的输出为6

#include <iostream>

using namespace std;

int z = 0;
    class A{
public:
    int a = 2;
    A(){
        a = 1; 
        z++;
    }
    A(const A& aa){
        a = 3;
        z += 2;
    }
    A& f(){return *this;}
};

void test(){
    {A a, b(a), c(A().f());}
    cout << z;
}

int main()
{
    test();

    return 0;
}

我了解除对象c初始化以外的所有行会发生什么:c(A().f())?如果您向我解释这一行,我将很高兴?

1 个答案:

答案 0 :(得分:2)

行像这样分解:

A a;     // Calls A::A();  (Default constructor. Has `z++;`, so `z` is now 1)
A b(a);  // Calls A::A(const A&);  (Copy constructor. `z += 2;`, so `z` is now 3)
A c(
  A()    // Calls A::A();  (`z++;`, `z` is now 4)
         // This creates a temporary `A` object
  .f()   // Just returns `*this`, the temporary. No copy made, nothing happens to `z`
);       // Calls A::A(const A&);  (`z += 2;`, `z` is now 6)