我已经看到以下代码段: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())
?如果您向我解释这一行,我将很高兴?
答案 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)