还有如果觉得有不足之处还望指出,谢谢…………
?
?
#include<iostream> using namespace std; class Object{ char* name; public: Object() { cout << "Objected is constructed.(无参数)" << endl; } Object(char* s) // { name = s;// cout << "Objected is constructed.(参数)" << endl; } Object( const Object& o) { //为对象申请内存并进行出错检查;(本文没有处理) //从对象o复制到本对象 name = o.name; cout << "Object is copied." << endl; } char* getName() { return name; } Object & operator = (const Object& lala) { name = lala.name; cout << "Object is operator =." << endl; return *this; } ~Object() { cout << "Object is destructed." << endl; } }; Object getObject( Object o) { cout << "getO" << endl;// return o; } Object getObject1( Object& o) { cout << "getO1" << endl;// return o; } Object& getObject2( Object& o) { cout << "getO2" << endl;// return o; } int main() { Object o("zhangsan"); Object o1; o1 = getObject( o); cout << endl; cout << "Object o2 = getObject(o):" << endl; Object o2 = getObject(o);//相当于Object o2(getObject(o)); cout << endl; cout << "o1 = getObject(o):" << endl; o1 = getObject(o); cout << endl << endl; //getObject1 cout << "getObject1:" << endl; Object o11; o11 = getObject1( o); cout << endl; cout << "Object o22 = getObject(o):" << endl; Object o22 = getObject1(o); cout << endl; cout << "o11 = getObject(o):" << endl; o11 = getObject(o); cout << endl << endl; //getObject2 cout << "getObject2:" << endl; Object o111; o111 = getObject2( o); cout << endl; cout << "Object o222 = getObject(o):" << endl; Object o222 = getObject2(o); cout << endl; cout << "o111 = getObject(o):" << endl; o111 = getObject(o); cout << "end" << endl; return 0; }?
?
?
Objected is constructed.(参数)
Objected is constructed.(无参数)
Object is copied. ? ? ? ? ? //每次传参都会构建临时对象
getO
Object is copied.
Object is destructed.
Object is operator =.
Object is destructed.
?
Object o2 = getObject(o):
Object is copied.
getO
Object is copied.
Object is destructed.
?
o1 = getObject(o):
Object is copied.
getO
Object is copied.
Object is destructed.
Object is operator =.
Object is destructed.
?
?
getObject1:
Objected is constructed.(无参数)
getO1
Object is copied.
Object is operator =.
Object is destructed.
?
Object o22 = getObject(o):
getO1
Object is copied.
?
o11 = getObject(o):
Object is copied.
getO
Object is copied.
Object is destructed.
Object is operator =.
Object is destructed.
?
?
getObject2:
Objected is constructed.(无参数)
getO2
Object is operator =.
?
Object o222 = getObject(o):
getO2
Object is copied.
?
o111 = getObject(o):
Object is copied.
getO
Object is copied.
Object is destructed.
Object is operator =.
Object is destructed.
end
?