<分区>
我有一个 protected 方法 Value
。在继任者中,我在公共(public)方法中重载了它。为什么我可以这样做?我认为,这是违反封装的。
class Foo {
public:
Foo(int a) : m_a(a) {};
virtual ~Foo() {};
void PrintValue() {
std::cout << Value() << std::endl;
}
protected:
virtual int Value() {
return m_a;
}
private:
int m_a;
};
class Bar : public Foo
{
public:
Bar(int a, int b) : Foo(a), m_b(b) {};
virtual ~Bar() {};
int Value() override {
return m_b;
}
private:
int m_b;
};
int main(int argc, char** argv)
{
Bar b(10, 20);
b.PrintValue();
std::cout << b.Value() << std::endl;
return 0;
}
输出:
20
20