#include <iostream>
using namespace std;
class B
{
public:
B()
{
cout<<"default constructor"<<endl;
}
B( const B &b )
{
cout << "copy constructor paramter: " << &b << endl;
cout << "copy constructor this: " << this << endl;
data = b.data;
}
B &operator=( const B &B )
{
data = B.data;
return *this;
}
~B()
{
cout << "~B() this: " << this << endl;
cout<<"destructed"<<endl;
}
B(int i):data(i) //B(int) works as a converter ( int -> instance of B)
{
cout << "B(int) this: " << this << endl;
cout<<"B(int) constructed by parameter " << data <<endl;
}
private:
int data;
};
B Play( B b)
{
cout << "Play( B b) func parameter: " << &b << endl;
return b;
}
int fn1()
{
int i = 0;
int j = 1;
return 1;
}
B getB()
{
B b;
return b;
}
int main(int argc, char* argv[]) //constructed by parameter 5
{
cout << "------------------------------------1-------------------------------------" << endl << endl;
//destructed B(5)形参析构
B t1 = Play(5); // Play返回时就调用拷贝构造函数直接创建 t1
cout << "t1: " << &t1 << endl;
cout << "------------------------------------2-------------------------------------" << endl << endl;
B t2 = Play(t1); // destructed t1形参析构
cout << "t2: " << &t2 << endl;
cout << "------------------------------------3-------------------------------------" << endl << endl;
cout << "begin:" << endl;
//B t3 = getB();
B t3 = 8; // 调用构造函数:B(int i), 不会先创建B(8)临时对象,然后再调用拷贝构造函数
_onexit(fn1); // 使得 main函数执行完后,执行 fn1 函数
system("pause");
return 0; // destructed t2 注意顺序!
} //destructed t1
输出结果: