在C++中所特有的另一种内置类型bool。它只是一种特殊情况,因为对于布尔值,我们并不需要像++这样的操作符。反之,我们需要特定的布尔操作符,例如&=和|=,因此,这个类型是单独定义的:
class Bool
{
public:
Bool(bool x=false)
: data_(x)
{
}
operator bool () const
{
return data_;
}
Bool& operator = (bool x)
{
data_ = x;
return *this;
}
Bool& operator &= (bool x)
{
data_ &= x;
return *this;
}
Bool& operator |= (bool x)
{
data_ |= x;
return *this;
}
private:
bool data_;
};
inline
std::ostream& operator << (std::ostream& os, Bool b)
{
if(b)
os << "True";
else
os << "False";
return os;
}到目前为止,使用Int,Unsigned,Double这样的类代替对应的小写字母内置类型的动机是可以避免在多个构造函数中对它们进行初始化。如果更宽泛的使用它们,例如表示传递给函数参数,结果将会是这样的。假设有一个接受unsigned类型(内置类型)的参数函数:
void SomeFunctionTaking_unsigned(unsigned u);
int i = 0; SomeFunctionTaking_unsigned(i);
void SomeFunctionTakingUnsigned(Unsigned u);
int i = 0; SomeFunctionTakingUnsigned(i);因此,在这种情况下,我们就自动获得了编译时类型安全的优点。
总结:
原文地址:http://blog.csdn.net/kerry0071/article/details/37989405