標籤:簡單實現 侯捷 image template eth 編程 進階 輸出 span
技術在於交流、溝通,轉載請註明出處並保持作品的完整性。
1.pointer-like class 類設計成指標那樣,可以當做指標來用,指標有兩個常用操作符(*和->),所以我們必須重載這兩個操作
/*簡單實現一下智能指標的*與 -> 操作符*/ template <class T> class shared_ptr_test { public: T& operator* () const //重載* { return *px; } T* operator->() const //重載 -> { return px; } shared_ptr_test(T* p):px(p){}; private: T * px; //指向class的一個指標 long pn; }; struct Foo { // ... void method(void) {}; }; int main() { shared_ptr_test<Foo> sp(new Foo); Foo f(*sp); //*作用後自動銷毀
//使px 指向Foo class sp->method(); //1.->作用後繼續填充
//2.== f->method(); sp->method() 會轉換成 px->method();即Foo::method() return 0; }
這個時候我們就可以像使用指標那樣使用這個class了
2.function-like classes 類可以像函數那樣使用,那我們必須重載 func operator call 即[()] 操作符
template<typename T>class lineFeed{public: void operator()(const T &x) { cout<<x<<endl; }};int main(){ int tmp[]={1,2,3,4,5}; for_each(tmp,tmp+5,lineFeed<int>()); return 0;}
輸出結果
參照<<侯捷 C++物件導向進階編程>>
C++物件導向進階編程(七)point-like classes和function-like classes