?? operator解引用的用法.txt
字號:
/*本程序選自thinking in c++ P510
*本程序在于說明operator->的使用方法。
*書上說:1.the operator-> is generally used when you want to make an object appear
* to be a pointer. an object like this is often called a smart pointer.
* 2.operator-> must be member function
* 3.operator-> must return an object(或是它的引用) that also has operator ->
or it must return pointer.
*/
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class Obj {
static int i,j;
public:
void f() const { cout << i++ << endl;}
void g() const { cout << j++ <<endl;}
};
//static member definitions
int Obj::i = 1;
int Obj::j = 2;
// container:
class ObjContainer {
vector< Obj * > a;
public:
void add( Obj * obj ) { a.push_back( obj );}
friend class SmartPointer; //友元聲明
};
class SmartPointer {
ObjContainer & oc;
int index;
public :
SmartPointer ( ObjContainer & objc ) : oc( objc ) { index = 0;}
//return value indicates end of list
bool operator ++() {
if ( index >= oc.a.size() ) return false;
if ( oc.a[++index] ==0 )return false;
return true;
}
bool operator ++(int){
return operator ++();
}
Obj * operator ->() const { //返回設計SmartPointer時想指向的對象的指針
assert( oc.a[ index ] != 0 );
return oc.a[ index ];
}
};
int main()
{
const int sz = 10;
Obj o[sz];
ObjContainer oc;
for ( int i = 0; i < sz ; i++)
oc.add( & o[i]);
SmartPointer sp(oc);
while ( sp++ )
{
sp->f();
sp->g();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -