我今天早些时候偶然发现了这个“问题”。
我有这个类,它包含一个转换运算符。像这样的东西:
class myClass {
public:
...
operator anotherClass*() { return anotherClassPtr; }
...
}
现在这一切都很好..直到我犯了这个愚蠢的错误:
void yetAnotherClass::foo(myClass* _p_class)
{
...
anotherClass* lp_anotherClass = (anotherClass*)_p_class;
...
}
我花了很长时间才弄清楚为什么 lp_AnotherClass ptr 被设置为非零值,而我确信 _p_class 中的 anotherClassPtr 为 0。
有什么我可以添加到 myClass 中的东西可以防止我犯这个错误吗? (即编译器会吐出一些错误)是否有可能阻止对象 ptr 被强制转换为其他对象?
最佳答案
anotherClass* lp_anotherClass = (anotherClass*)_p_class;
首先,你不应该使用 C 风格的转换。使用 C++-style throw 。那会节省您的时间,因为编译器会立即告诉您问题所在:
auto* lp_anotherClass = static_cast<anotherClass*>(_p_class); //ERROR
其次,更喜欢使用显式
转换函数:
explicit operator anotherClass*() { return anotherClassPtr; }
为什么我建议使用explicit
转换函数,因为它避免了implicit 转换产生的细微错误,此外,它还增加了代码的可读性!
请注意,explicit
转换函数是 C++11 的一个特性。
关于c++ - 转换运算符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402958/