C++ 沉思錄也算是C++中的經(jīng)典書籍,其中介紹OO思想的我覺得很好,但是全書中貫穿了handle,使用引用計數(shù)等,也有點不適合現(xiàn)代C++的設計思想。這里使用shared_ptr 智能指針改寫了“句柄”這一章的程序,明顯使代碼量下降,而且管理方便。下面來看代碼: #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{ //句柄類 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對象并未復制,只是引用計數(shù)加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(); } //輸出引用個數(shù) 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; //此處調(diào)用的是構造函數(shù)Handle(const Handle& h) h2.x(3).y(4); //此處的特殊寫法是因為寫xy函數(shù)內(nèi)返回了對象 Handle h3(5,6); //此處調(diào)用Handle的賦值運算符重載函數(shù)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 可見這里的結果和“句柄”這里的完全一樣。 |
|