<分区>
有一部分 C++ 代码我不是很理解。 也不知道应该去哪里找相关资料,所以我决定问一个问题。
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test();
Test(Test const & src);
Test& operator=(const Test& rhs);
Test test();
int x;
};
Test::Test()
{
cout << "Constructor has been called" << endl;
}
Test::Test(Test const & src)
{
cout << "Copy constructor has been called" << endl;
}
Test& Test::operator=(const Test& rhs)
{
cout << "Assignment operator" << endl;
}
Test Test::test()
{
return Test();
}
int main()
{
Test a;
Test b = a.test();
return 0;
}
为什么我得到的输入是
Constructor has been called
Constructor has been called
? a.test() 通过调用“Test()”创建一个新实例,这就是显示第二条消息的原因。但是为什么没有调用复制构造函数或赋值? 如果我将“return Test()”更改为“return *(new Test())”,则会调用复制构造函数。
那为什么不是第一次调用呢?