【问题标题】:Cannot use protected operator== in derived class不能在派生类中使用受保护的 operator==
【发布时间】:2017-09-14 20:05:53
【问题描述】:
#include <iostream>

class Foo {
public:
    int m_foo;
    Foo(int a_foo) : m_foo(a_foo) {}

protected:
    bool operator==(const Foo& a) const {
        std::cout << "Foo: " << m_foo << " == " << a.m_foo << '\n';
        return m_foo == a.m_foo;
    }
};

class Bar : public Foo {
public:
    int m_bar;
    Bar(int a_foo, int a_bar) :
        Foo(a_foo),
        m_bar(a_bar)
    {}

    bool operator==(const Bar& a) const {
        std::cout << "Bar: " << m_foo << ", " << m_bar << " == " << a.m_foo << ", " << a.m_bar << '\n';
        return (const Foo&)*this == (const Foo&)a &&
               m_bar             == a.m_bar;
    }
};

int main() {
    Bar a(1, 1);
    Bar b(1, 2);
    Bar c(2, 2);

    std::cout << (a == a) << '\n';
    std::cout << (a == b) << '\n';
    std::cout << (a == c) << '\n';

    return 0;
}

在我的真实代码中,Foo 是一个可以实例化但不允许使用operator== 的类,因此我将其设为protected。执行此操作时出现编译器错误:

foo.cpp: In member function ‘bool Bar::operator==(const Bar&) const’:
foo.cpp:9:7: error: ‘bool Foo::operator==(const Foo&) const’ is protected
  bool operator==(const Foo& a) const {
       ^
foo.cpp:25:43: error: within this context
   return (const Foo&)*this == (const Foo&)a &&
                                           ^

为什么不允许这样做?派生类不应该可以使用protected方法吗?

【问题讨论】:

  • return (const Foo&amp;)*this == (const Foo&amp;)a -- 不确定,但== 似乎没有在基类上运行。这是两个独立的对象,*thisa。 @MichaelBurr 给出的答案实际上在调用中使用了基类Foo::
  • @PaulMcKenzie,这种说法是有道理的,它更像是operator==(const Foo&amp; l, const Foo&amp; r) 签名,但我原以为(const Foo&amp;)*this 会产生一个Foo,然后是它的方法会被使用
  • @PaulMcKenzie,我考虑了更多,并决定因为我没有定义两个对象相等运算符,所以不应该有一个函数/方法来比较两个对象。虽然仍然很困惑
  • 我认为stackoverflow.com/questions/16785069/… 可以回答您的问题。
  • @DineshMaurya,是的,现在说得通了,谢谢

标签: c++


【解决方案1】:

我无法回答为什么(目前),但这种替代语法可以满足您的需求:

return Foo::operator==(a) &&  (m_bar == a.m_bar);

【讨论】:

  • 我仍然想知道答案,但出于所有实际目的,这可行,+1
  • 我必须刷新我对细节的记忆,但我很确定这与有关 ADL(Argument Dependent Lookup aka Koenig 查找)的规则有关。
  • Dinesh Maurya 指出了 cmets 中的原因,继续接受您的回答,因为这是问题的解决方案
猜你喜欢
  • 2010-09-30
  • 2014-12-26
  • 2023-03-07
  • 2021-03-24
  • 1970-01-01
  • 2014-09-12
  • 2013-03-05
  • 1970-01-01
  • 2018-11-27
相关资源
最近更新 更多