代码和解释:
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class test{
int *p;
public:
test(int value){
p = new int(value);
cout<<"Execute Constructor>>"<<endl;
cout<<"p的地址为"<<&p<<";p的值为"<<p <<" ;*p的值为"<<*p<<endl;
}
~test(){
cout<<"<<Execute Destructor"<<endl;
delete p;//delete p只是释放指针指向的内存所存储的数据,并不会改变指针所保存的地址
p = NULL;//将p所指向的地址置为null
}
test(const test &other){
cout<<"Execute Copy Constructor>>"<<endl;
p = new int(*other.p);
}
test & operator = (const test &pt){//此时 test &pt是对第二次构造函数产生的对象的引用,其中的*p是5;test &是对复制构造函数产生的对象的引用
cout<<"前p的地址为"<<&p<<";前p的值为"<<p <<" ;前*p的值为"<<*p<<endl;//此时的p是指复制构造函数产生的对象的p,即*p为33
p = new int(*pt.p);//利用new开辟一块新的内存块(并未产生新的对象);并用*pt.p的值初始化;最后将复制构造函数产生的对象的成员p指向该块内存空间。
cout<<"后p的地址为"<<&p<<";后p的值为"<<p <<" ;后*p的值为"<<*p<<endl;
cout<<"this的值为"<<this<<" ;*this的值为"<<*this<<endl;
cout<<"离开第二次调用构造函数产生新对象的作用域,调用析构函数: ";
return *this;//此处返回的对象复制构造函数产生的对象的值
}
bool operator == (const test &other){
return p == other.p;
}
friend ostream & operator << ( ostream &os, test &A ){
os << *A.p;
return os;
}
void printvalue(){
cout<<"the value is "<<*p<<endl;
}
};
void func(test t){
cout<<"对象t的值为 "<< t <<" ;对象t的地址为 "<< &t<<endl;
cout<<"重载运算符右值初始化,第二次调用构造函数和产生新对象:";
t.operator=(5);//从右到左执行;(5)调用构造函数产生一个对象;返回后,t.operator=再调用重载运算符函数
cout<<"对象t的值为 "<< t <<" ;对象t的地址为 "<< &t<<endl;
cout<<"离开复制构造函数产生对象的作用域,调用析构函数: ";
}
int _tmain(int argc, _TCHAR* argv[])
{
test t1 = 33;//初始化对象为33:第一次调用构造函数
cout<<"即将调用复制构造函数产生对象: ";
func(t1);//这里是传值的调用,也就是复制一份t1:调用复制构造函数
t1.printvalue();
return 0;
}