【问题标题】:Returning reference to class with overloaded private & operator?使用重载的私有&运算符返回对类的引用?
【发布时间】:2011-01-13 11:38:46
【问题描述】:

我有一个名为 Property 的类(来自外部库 == 无法修改),它具有私有重载 & 运算符。我在另一个类中使用这个类作为属性,并且(出于理智的原因)我想通过 Get 方法返回对该属性的引用。但是,我遇到了无法处理的“无法访问在类中声明的私有成员”错误。有没有办法绕过它 - 不公开财产。

// Some external class.
class Property
{
    Property*   operator&() const;
};

class MyClass
{
protected:
    Property m_Property;

public:

    // error C2248: 'Property::operator &' : cannot access private member declared in class 'Property'
    const Property& GetProperty() const
    {
        return *& this->m_Property;
    }
};

【问题讨论】:

    标签: c++ reference operators private operator-keyword


    【解决方案1】:

    我可能遗漏了什么,但为什么不简单地说:

    const Property& GetProperty() const
    {
      return this->m_Property;
    }
    

    operator& 是私有的这一事实清楚地表明你不应该调用它。

    【讨论】:

    • 你是对的,当然。我想咖啡太多了;)谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    相关资源
    最近更新 更多