賦值和初始化

  今天在學習拷貝析構的時候遇到的問題:ios

  

 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 }
相關文章
相關標籤/搜索