我想隐藏一个虚拟方法而不是覆盖。我知道出于历史/兼容性原因,覆盖说明符是可选的,并且覆盖会隐式发生。 为了停止覆盖,我通常通过添加默认的“ Dummy”参数来调整签名。有更好的方法吗?
假设此代码:
#include <iostream>
class A{
public:
virtual void Foo()
{
std::cout << "A::Foo";
}
};
class B : public A
{
public:
void Foo() /*not override, just hide*/
{
std::cout << "B::Foo";
}
};
int main()
{
B b{};
A& a = b;
a.Foo(); //should print A::Foo - but prints B::Foo
}
我到目前为止所做的是:
#include <iostream>
class A{
public:
virtual void Foo()
{
std::cout << "A::Foo";
}
};
template<typename T>
class reintroduce{};
class B : public A
{
public:
void Foo(reintroduce<B> = {}) /*not override, just hide*/
{
std::cout << "B::Foo";
}
};
int main()
{
B b{};
A& a = b;
a.Foo(); //should print A::Foo
}
答案 0 :(得分:0)
关于“ 隐藏”的要求的问题不是很清楚,但是以下有效地“ 隐藏”是派生类中继承的方法,同时不更改其可见性/ accessibility在基类中。
#include <iostream>
class A {
public:
virtual void Foo()
{ std::cout << "A::Foo"; }
};
class B : public A
{
private:
using A::Foo;
};
int main()
{
B b;
b.Foo(); // error, cannot access private member
b.A::Foo(); // ok, calls A::Foo
A& a = b;
a.Foo(); // ok, calls A::Foo
}