conversion operator
分為 implicit 和 explicit
implicit : operator int() { return value; }
explicit : explicit operator int() { return value; }
operator int() { return value; }
將 object 自動轉為整數型態,其值為 value
使用 explicit 的 conversion operator 時,要記得加 static_cast
但 bool 在判斷式時除外
例如:
#include <iostream>
using std::cout;
using std::endl;
class convOper
{
public:
operator int() const { cout << "you call int()" << endl; return value; }
explicit operator bool() const { cout << "you call bool()" << endl; return good; }
private:
int value = 0;
bool good = true;
};
int main()
{
convOper co;
if(co == 0)
{
cout << "value is 0" << endl;
}
if(static_cast<bool>(co) == true)
{
cout << "good is true" << endl;
}
if(co)
{
cout << "no error occurred!" << endl;
}
return 0;
}
相關例子
while( cin >> x )
{
}
留言列表