C++ 沉思錄也算是C++中的經(jīng)典書(shū)籍,其中介紹OO思想的我覺(jué)得很好,但是全書(shū)中貫穿了handle,使用引用計數等,也有點(diǎn)不適合現代C++的設計思想。這里使用shared_ptr 智能指針改寫(xiě)了“句柄”這一章的程序,明顯使代碼量下降,而且管理方便。下面來(lái)看代碼:
#include <iostream>#include <memory>using namespace std;class Point{public: Point() : xval(0),yval(0){}; Point(int x, int y): xval(x), yval(y){}; Point(const Point & p) { if(this == &p) return ; this->xval = p.x(); this->yval = p.y(); } int x() const {return xval;}; int y() const {return yval;}; Point& x(int xv) { xval = xv; return *this; }; Point& y(int yv) { yval = yv; return *this; };private: int xval, yval;};class Handle{ //句柄類(lèi)public: Handle(): up(new Point){}; Handle(int x,int y): up(new Point(x,y)){};//按創(chuàng )建Point的方式構造handle,handle->UPoint->Point Handle(const Point& p): up(new Point(p)){};//創(chuàng )建Point的副本 Handle(const Handle& h): up(h.up){ /*++up->u;*/ };//此處復制的是handle,但是底層的point對象并未復制,只是引用計數加1 Handle& operator=(const Handle& h) { up = h.up; return *this; }; ~Handle() { }; int x() const{return up->x();}; Handle& x(int xv) { up->x(xv); return *this; }; int y() const{return up->y();}; Handle& y(int yv) { up->y(yv); return *this; }; int OutputU() { return up.use_count(); } //輸出引用個(gè)數private: shared_ptr<Point> up;};int main(){ //Point *p = new Point(8,9); Point p(8,9); //Point p1 = p.x(88); //Point *pp = &p; Handle h1(1,2); Handle h2 = h1; //此處調用的是構造函數Handle(const Handle& h) h2.x(3).y(4); //此處的特殊寫(xiě)法是因為寫(xiě)xy函數內返回了對象 Handle h3(5,6); //此處調用Handle的賦值運算符重載函數Handle& operator=(const Handle& h) h1 = h3; Handle h4(p); Handle h5(h4); h4.x(7).y(8); //Handle h5(p1); //Handle h5 = h4; cout <<"h1(" << h1.x() <<":"<< h1.y() << "):" << h1.OutputU() <<endl; cout <<"h2(" << h2.x() <<":"<< h2.y() << "):" << h2.OutputU() <<endl; cout <<"h3(" << h3.x() <<":"<< h3.y() << "):" << h3.OutputU() <<endl; cout <<"h4(" << h4.x() <<":"<< h4.y() << "):" << h4.OutputU() <<endl; cout <<"h5(" << h5.x() <<":"<< h5.y() << "):" << h5.OutputU() <<endl; //delete pp; //不能這樣,不是用new分配的空間 //cout <<"h5(" << h5.x() <<":"<< h5.y() << "):" << h5.OutputU() <<endl; cout<<p.x()<<" "<<p.y()<<endl; //cout<<&p1<<endl; return 0;}
運行結果:
C:\Windows\system32\cmd.exe /c handle_sharedptr.exe
h1(5:6):2
h2(3:4):1
h3(5:6):2
h4(7:8):2
h5(7:8):2
8 9
Hit any key to close this window...
可見(jiàn)這里的結果和“句柄”這里的完全一樣。
聯(lián)系客服