![]() |
#2
rjsp2013-05-14 12:10
|

#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;
return testInFunc;
}
int main()
{
TestConstructor test1 = testFunc();
return 0;
}
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;
return testInFunc;
}
int main()
{
TestConstructor test1 = testFunc();
return 0;
}
}
输出结果为:
TestConstructor()
TestConstructor(const TestConstructor&)
~TestConstructor()
~TestConstructor()
我明白:第一条TestConstructor()是创建testFunc()中的对象 第二条输出TestConstructor(const TestConstructor&)
是 创建临时对象; 第三条~TestConstructor()是析构testFunc()中的对象;
后面就纳闷了: 返回到 TestConstructor test1 = testFunc();时,不是应该执行复制构造函数将临时对象复制给test1吗?怎么没显示TestConstructor(const TestConstructor&)?然后应该出现两个析构函数,一个析构临时对象,另一个析构test1吗?