C++:在相等测试中使用基类的私有成员
我想要编译以下内容,但它没有:
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
。
I would like the following to compile, but it does not:
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
}
};
Is there any way to make this work? I can't modify Odp
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Odp
重载operator*
以返回m_p
。您可以在*this
和rhs
上调用运算符:operator*
重载有点不寻常,但是:它可能应该返回*m_p
相反,因为operator->
返回m_p
(这将导致您的类具有一致的类似指针的语义)。如果您这样做,则必须执行以下操作来进行比较:这有点混乱,如果一元
&
重载于,则不一定有效T
(但是,你真的、真的不应该这样做......)。您还可以通过显式调用operator->
来获取指针,这可能更好:真正的问题是,“这个
Odp
是什么,为什么要使用它,为什么你不能修改它?”在一个不相关的注释中,您的
operator==
应该实现为 const 成员函数,或者最好作为友元函数实现:在另一个不相关的注释中,重载一元
&
> 几乎肯定是一个坏主意。Odp
overloadsoperator*
to returnm_p
. You can invoke the operator on*this
andrhs
:The
operator*
overload is a bit unusual, however: it should probably return*m_p
instead, sinceoperator->
returnsm_p
(this would result in your class having consistent pointer-like semantics). If you did this, you would then have to do the following to do the comparison:This is getting a bit messy, and it won't necessarily work if the unary
&
is overloaded forT
(but, you really, really shouldn't do that...). You can also obtain the pointer by explicitly callingoperator->
, which might be preferable:The real question is, "what is this
Odp
, why are you using it, and why can you not modify it?"On an unrelated note, your
operator==
should either be implemented as a const member function or, preferably, as a friend function:On another unrelated note, overloading the unary
&
is almost certainly a bad idea.编译器告诉您 m_p 是私有的。如果要访问派生类中的 m_p,则需要将其设置为受保护或公共。
The compiler is telling you that m_p is private. If you want to access m_p in the derived class you need to make it either protected or public.
由于 Odp 在其方法中免费给出了指针(甚至是它的地址,天哪!这就像用很多锁制作门,然后将钥匙交给周围的每个小偷),你可以这样做
如果 Odp 实现了自己的比较运算符,您可以像这样使用它:
Since
Odp
is giving the pointer out for free in its methods (even the address of it, OMG! it's like making door with many locks and then giving the keys to every thief around), you can just doHad
Odp
implemented its own comparison operator, you could use it like this:如果无法修改
Odp
,可以显式调用operator->()
。它返回您需要的内容并且应该内联。If you can't modify
Odp
, you can calloperator->()
explicitly. It returns what you need and should get inlined.