c++ - 转换运算符问题

标签 c++ operator-overloading

我今天早些时候偶然发现了这个“问题”。

我有这个类,它包含一个转换运算符。像这样的东西:

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/

相关文章:

c++ - 为什么我的带有数组参数的方法不能正常工作? (C++)

C++:具有比较运算符重载的模板类

c++ - 重载运算符后如何访问标准*此行为*?

c++ - 序列化其中包含可序列化嵌套类的类,出现奇怪的编译错误

c++ - 指向类的指针

c++ - Xcode 4.2 无法识别 C++ 原始字符串文字?

c++ - std::condition_variable 的谓词是否在锁下执行?

c# - 只有当变量类型是派生类时才有效?

c++ - 解锁保护(或 boost::reverse_lock)是反模式吗?为什么?

c++ - Qt - 如何从另一个子窗口或小部件访问主窗口?