转换运算符问题

Lie*_*uwe 2 c++ operator-overloading

我今天早些时候偶然发现了这个"问题".

我有这个类,它包含一个转换运算符.就像是:

class myClass {
public:
    ...

    operator anotherClass*() { return anotherClassPtr; }

    ...
}
Run Code Online (Sandbox Code Playgroud)

现在这一切都很好..直到我犯了这个愚蠢的错误:

void yetAnotherClass::foo(myClass* _p_class) 
{
  ...

  anotherClass* lp_anotherClass = (anotherClass*)_p_class;

  ...
}
Run Code Online (Sandbox Code Playgroud)

我花了很长时间才弄清楚为什么lp_AnotherClass ptr被设置为非零而我确信_p_class中的anotherClassPtr为0.

有没有什么我可以添加到myClass会阻止我犯这个错误?(即编译器会吐出一些错误)是否有可能阻止对象ptr被强制转换为其他东西?

Naw*_*waz 6

anotherClass* lp_anotherClass = (anotherClass*)_p_class;
Run Code Online (Sandbox Code Playgroud)

首先,你不应该使用C风格的演员表.使用C++ - 样式转换.这样可以节省您的时间,因为编译器会立即告诉您问题:

auto* lp_anotherClass = static_cast<anotherClass*>(_p_class); //ERROR
Run Code Online (Sandbox Code Playgroud)

其次,更喜欢使用explicit转换功能:

explicit operator anotherClass*() { return anotherClassPtr; }
Run Code Online (Sandbox Code Playgroud)

为什么我建议使用explicit转换函数,因为它避免了隐式转换带来的细微错误,此外,它还提高了代码的可读性!

请注意,explicit转换函数是C++ 11的一项功能.