看如下代碼:
代碼如下:
#include<iostream>
class TestConstructor
{
public:
TestConstructor()
{
std::cout<<"TestConstructor()"<<std::endl;
}
~TestConstructor()
{
std::cout<<"~TestConstructor()"<<std::endl;
}
TestConstructor(const TestConstructor& testObj)
{
std::cout<<"TestConstructor(const TestConstructor&)"<<std::endl;
}
TestConstructor& operator = (const TestConstructor& testObj)
{
std::cout<<"TestConstructor& operator = (const TestConstructor& testObj)"<<std::endl;
return *this;
}
};
TestConstructor testFunc()
{
TestConstructor testInFunc; //3、調用TestConstructor() 生成對象testInFunc
return testInFunc; //4、調用TestConstructor(const TestConstructor&) 生成臨時對象
//5、調用析構函數,析構對象testInFunc
}
int main()
{
TestConstructor test; //1、調用TestConstructor() 生成對象test
test = testFunc(); //2、調用testFunc() //6、調用等號把臨時對象復制給對象test //7、調用析構函數,析構臨時對象
return 0; //8、調用析構函數,析構對象test
}
看輸出:
有注釋,有輸出。執行細節,一目了然了吧