C++:在相等性测试中使用基类的私有(private)成员

标签 c++ inheritance operator-overloading

我想编译以下内容,但它没有:

template <typename T>
struct Odp
{
public:
    operator*() const
    {
        return m_p;
    }

    T* operator->() const
    {
        return m_p;
    }

    T** operator&()
    {
        return &m_p;
    }

private:
        T* m_p;

};

struct Ftw : public Odp<int>
{
    bool operator==(const Ftw& rhs)
    {
        return m_p == rhs.m_p; // C2248 cannot access private member
    } 
};

有什么办法可以实现吗?我无法修改 Odp

最佳答案

Odp 重载 operator* 以返回 m_p。您可以在 *thisrhs 上调用运算符:

struct Ftw : public Odp<int>
{
    bool operator==(const Ftw& rhs) const
    {
        return **this == *rhs;
    } 
};

operator* 重载有点不寻常,但是:它可能应该返回 *m_p,因为 operator-> 返回 m_p(这将导致您的类具有一致的类似指针的语义)。如果这样做,则必须执行以下操作才能进行比较:

return &**this == &*rhs; // or explicitly as:
return &this->operator*() == &rhs.operator*();

这有点困惑,如果一元 &T 重载,它不一定会起作用(但是,你真的,真的 不应该那样做...)。您还可以通过显式调用 operator-> 来获取指针,这可能更可取:

return this->operator->() == rhs.operator->();

真正的问题是,“这个 Odp 是什么,为什么要使用它,为什么不能修改它?”


顺便说一句,您的 operator== 应该作为常量成员函数实现,或者最好作为友元函数实现:

bool operator==(const Ftw& rhs) const { /* ... */ }
friend bool operator==(const Ftw& lhs, const Ftw& rhs) { /* ... */ }

另一个不相关的说明,重载一元 & 几乎肯定是个坏主意。

关于C++:在相等性测试中使用基类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410854/

相关文章:

c++ - 显式运算符 bool 错误

c++ - 矩阵乘法中最大运算的模运算

c++ - 用模板替换标量失败

c++ - 模板默认参数丢失其引用类型

C# 实现接口(interface)定义的派生类型?

c++ - 如何编写 C++ 转换运算符返回对数组的引用?

copy - 按值重载运算符会导致使用移动的值

C++ : Undefined symbols for architecture x86_64 on MacOS Mountain Lion

Javascript::为什么 Object.hasOwnProperty ('caller' ) 返回 true?

java - 如何让instanceof区分子类和父类?