【发布时间】:2011-01-09 21:30:56
【问题描述】:
我有以下课程:
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(),这会导致未定义的行为。
但是为什么首先调用operator bool()?
【问题讨论】:
标签: c++ visual-c++ casting operators