我想编译以下内容,但它没有:
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
。您可以在 *this
和 rhs
上调用运算符:
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/