65,210
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
//using namespace std;
//safe bool idiom示例
class Testable {
bool ok_;
public://加了个它
typedef void (Testable::*bool_type)();// const;//去掉原来的全部const,不影响输出
void this_type_does_not_support_comparisons() //const //去掉原来的全部const
{}
public:
explicit Testable(bool b=true):ok_(b) {}
//safe bool idiom
operator bool_type() //const //去掉原来的全部const
{
return ok_==true ?
&Testable::this_type_does_not_support_comparisons : 0;
}
};
//对比1
typedef void (*bool_type2)();
void this_type_does_not_support_comparisons2()
{
}
class Testable2 {
bool ok_;
public:
public:
explicit Testable2(bool b=true):ok_(b) {}
operator bool_type2()
{
return ok_==true ?
&this_type_does_not_support_comparisons2 : 0;
}
};
//对比2
typedef void (*PFUN)();
void comparisons()
{
}
int main()
{
Testable tt(true);
std::cout<< tt <<std::endl;//输出1。为什么tt被当成bool型输出?这个是关键问题。
//std::cout<< tt.operator bool_type() <<std::endl;//附带问题:如何显示调用这个转换操作符?
Testable2 tt2(true);
std::cout<< tt2 <<std::endl;//为什么不输出1?与Testable的区别何在?
std::cout<< tt2.operator bool_type2() <<std::endl;
std::cout << ( true?&comparisons:0 ) << std::endl;//为什么不输出1?
std::cout << reinterpret_cast<PFUN>( true?&comparisons:0 ) << std::endl;//为什么不输出1?
std::cout << static_cast<PFUN>( true?&comparisons:0 ) << std::endl;//为什么不输出1?
return 0;
}