【问题标题】:Conversion operator issues转换运算符问题
【发布时间】:2013-01-18 16:12:43
【问题描述】:

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

我有这个类,它包含一个转换运算符。比如:

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 被强制转换为其他东西?

【问题讨论】:

    标签: c++ operator-overloading


    【解决方案1】:
    anotherClass* lp_anotherClass = (anotherClass*)_p_class;
    

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

    auto* lp_anotherClass = static_cast<anotherClass*>(_p_class); //ERROR
    

    其次,更喜欢使用explicit转换函数:

    explicit operator anotherClass*() { return anotherClassPtr; }
    

    为什么我推荐explicit转换函数,因为它避免了隐式转换产生的细微错误,另外,它增加了代码的可读性!

    请注意,explicit 转换函数是 C++11 功能。

    【讨论】:

    • 感谢您的解释。不幸的是,恰当命名的“myClass”实际上并不是我的……所以我无法将其更改为显式运算符(我们还没有切换到 C++11)。
    • @Lieuwe:没关系。切换到 C++11 后,开始采用更好的习语。暂时可以写to_anotherClass()之类的东西。这个想法是一样的:明确!
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2020-07-18
    相关资源
    最近更新 更多