无法在派生类

时间:2017-04-18 20:14:42

标签: c++

#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方法?

1 个答案:

答案 0 :(得分:3)

我无法回答原因(但),但这种替代语法可以满足您的需求:

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