C++ 为什么是;运算符bool();当我强制转换为“时调用”;长“;?
我有以下课程:C++ 为什么是;运算符bool();当我强制转换为“时调用”;长“;?,c++,visual-c++,casting,operators,C++,Visual C++,Casting,Operators,我有以下课程: class MyClass { public: MyClass( char* what ) : controlled( what ) {} ~MyClass() { delete[] controlled; } operator char*() const { return controlled; } operator void*() const { return controlled; } operator bool() const { retur
class MyClass {
public:
MyClass( char* what ) : controlled( what ) {}
~MyClass() { delete[] controlled; }
operator char*() const { return controlled; }
operator void*() const { return controlled; }
operator bool() const { return controlled != 0; }
private:
char* controlled;
};
这是使用具有以下TypeDef的Microsoft SDK编译的:
typedef long LONG_PTR;
typedef LONG_PTR LPARAM;
调用代码执行以下操作:
MyClass instance( new char[1000] );
LPARAM castResult = (LPARAM)instance;
// Then we send message intending to pass the address of the buffer inside MyClass
::SendMessage( window, message, wParam, castResult );
突然调用castResult
为1
-MyClass::operator bool()
,它返回true
,并转换为1
。因此,我将1
传递到SendMessage()
中,而不是传递地址,这会导致未定义的行为
但是为什么要首先调用
操作符bool()
?这是使用操作符bool的已知陷阱之一,这是C继承的余震。你一定会从阅读有关这本书中受益匪浅
一般来说,您没有提供任何其他可匹配的强制转换操作符,而bool(不幸)被视为算术强制转换的良好源代码。
操作符bool
是最佳匹配,因为与bool
不同,没有显式强制转换,char*
和void*
无法转换为long
:
long L1 = (void*)instance; // error
long L2 = (char*)instance; // error
long L3 = (bool)instance; // ok
不能将
T*
隐式强制转换为long。但你可以投一个很长的球
因此使用了运算符bool
您必须定义一个
运算符LPARAM
,或者删除所有转换运算符。如果您希望允许在布尔上下文中评估对象(在标准C++库中使用的对象,但仅给出代码< STD::CUT),则认为<>代码>操作符Value*/Cuth>被认为是相对良性的。