今天在學習拷貝析構的時候遇到的問題:
1 #include <iostream> 2 using std::cout; using std::cin; using std::endl; 3 #include "HasPtr.h" 4 5 int main() 6 { 7 HasPtr ha("Halo"); 8 cout<<ha.getPs()<<endl; 9 HasPtr copy_ha(ha); 10 cout<<copy_ha.getPs()<<endl; 11 HasPtr assign_ha; 12 //HasPtr assign_ha = ha; 13 assign_ha = ha; 14 cout<<assign_ha.getPs()<<endl; 15 return 0; 16 }
如果按照第12行那樣寫的話就是初始化程序,這樣的話是不會呼叫多載的拷貝賦值運算子,而是呼叫拷貝建構式,如果按照第11和13行這樣寫,第13行是賦值操作,所以會呼叫多載的拷貝賦值運算子,以下是運行結果(圖1是直接初始化,圖二是先定義assign_ha然后賦值,):


下面是類的頭檔案和實作:
1 //HasPtr.h 2 #ifndef HASPTR_H 3 #define HASPTR_H 4 5 #include <iostream> 6 #include <string> 7 8 class HasPtr 9 { 10 public: 11 HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0) { } 12 HasPtr(const HasPtr&); 13 std::string* getPs() const { return ps; } //由于原本就不可以對私有成員進行操作,所以不必回傳參考 14 int getI() const { return i; } 15 HasPtr& operator=(const HasPtr&); 16 ~HasPtr(); 17 private: 18 std::string *ps; 19 int i; 20 }; 21 22 #endif // HASPTR_H
1 //HasPtr.cpp 2 #include "HasPtr.h" 3 4 HasPtr::HasPtr(const HasPtr& h) 5 { 6 ps = new std::string(*(h.ps)); 7 i = h.i; 8 std::cout<<"call the copyCtor."<<std::endl; 9 } 10 11 HasPtr::~HasPtr() 12 { 13 std::cout<<"call the dtor."<<std::endl; 14 delete ps; 15 } 16 17 HasPtr& HasPtr::operator= (const HasPtr& rhs) 18 { 19 std::cout<<"call the assignment operator."<<std::endl; 20 ps = new std::string(*(rhs.ps)); 21 i = rhs.i; 22 return *this; 23 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/86630.html
標籤:C++
