代碼1
#include <iostream>
using namespace std;
class TestV2
{
public:
TestV2(int a = 10) :ma(a){ cout << "TestV2(int) " << ma <<" 物件地址="<<this << endl; }
~TestV2() { cout << "~TestV2()" << ma <<"析構物件地址="<<this<<endl; }
TestV2(const TestV2 & t) :ma(t.ma)
{
cout << "TestV2(const Test & t),拷貝構造地址 原物件地址"<<&t <<"目標物件地址="<<this << endl;
}
TestV2 & operator =(const TestV2 & t) {
if (this == &t) { return *this; }
ma = t.ma;
cout << "operator= 源物件地址="<< &t<< "目標物件地址=" <<this << endl;
return *this;
}
int getData() { return ma; }
private:
int ma;
};
TestV2 getObject(TestV2 tep) {
int data = https://www.cnblogs.com/erichome/p/tep.getData();
TestV2 temp(data + 100);
return temp;
}
int main() {
TestV2 t1(20);
TestV2 t2(20);
t2=getObject(t1);
cout <<"t2物件地址= "<< &t2 << endl;
system("pause");
return 0;
}
看上面代碼執行效果

代碼2
#include <iostream>
using namespace std;
class TestV2
{
public:
TestV2(int a = 10) :ma(a){ cout << "TestV2(int) " << ma <<" 物件地址="<<this << endl; }
~TestV2() { cout << "~TestV2()" << ma <<"析構物件地址="<<this<<endl; }
TestV2(const TestV2 & t) :ma(t.ma){ cout << "TestV2(const Test & t),拷貝構造地址 原物件地址"<<&t <<"目標物件地址="<<this << endl; }
TestV2 & operator =(const TestV2 & t) {
if (this == &t) { return *this; }
ma = t.ma;
cout << "operator=源物件地址="<< &t<< "目標物件地址=" <<this << endl;
return *this;
}
int getData() { return ma; }
private:
int ma;
};
TestV2 getObject(TestV2 tep) {
int data = https://www.cnblogs.com/erichome/p/tep.getData();
TestV2 temp(data + 100);
return temp;
}
int main() {
TestV2 t1(20);
TestV2 t2(20);
TestV2 t3=getObject(t2);
cout <<"t3物件地址= "<< &t3 << endl;//物件3的地址帶入getObject()函式,TestV2 temp(data + 100) 直接在t3上構建物件
system("pause");
return 0;
}

針對上面優化
1:函式引數傳遞程序匯總,物件優先按參考傳遞,不要按值傳遞(可以解決 形參的拷貝構造,和形參的析構)
2:
TestV2 getObject(TestV2 &tep) {
int data = https://www.cnblogs.com/erichome/p/tep.getData();
TestV2 temp(data + 100);
return temp;
}
改為
TestV2 getObject(TestV2 &tep) {
return TestV2 temp(tep.getData()+ 100);//用一個臨時物件
}
//用一個臨時物件拷貝構造一個新的物件的時候,這個臨時物件會被編譯器優化掉,不再產生

3:接受函式回傳是物件的時候,優先用初始化的方式接受,不要用賦值的方式接受
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/538893.html
標籤:C++
下一篇:Linux 基礎-檔案權限與屬性
