用纯说明符覆盖虚函数是否有效?
Is it valid to override virtual function with pure specifier?
注意:我不问这样做是否合理,或者这是否是好的设计。我只是问这是否是定义明确的行为,结果是否符合预期。
我发现了以下 class 层次结构:
struct A
{
virtual void foo() = 0;
};
struct B: public A
{
void foo() override
{
std::cout << "B::foo()\n";
}
};
struct C: public B
{
virtual void foo() = 0;
};
struct D: public C
{
void foo() override
{
std::cout << "D::foo()\n";
}
};
int main()
{
A* d = new D;
d->foo(); //outputs "D::foo()"
// A* c = new C; // doesn't compile as expected
}
这段代码定义的好吗?我们可以用纯说明符覆盖定义吗?
当前标准草案的
[Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. — end note]
甚至 C++11 标准 中也包含完全相同的注释。所以,答案是是的,它是有效的。
注意:我不问这样做是否合理,或者这是否是好的设计。我只是问这是否是定义明确的行为,结果是否符合预期。
我发现了以下 class 层次结构:
struct A
{
virtual void foo() = 0;
};
struct B: public A
{
void foo() override
{
std::cout << "B::foo()\n";
}
};
struct C: public B
{
virtual void foo() = 0;
};
struct D: public C
{
void foo() override
{
std::cout << "D::foo()\n";
}
};
int main()
{
A* d = new D;
d->foo(); //outputs "D::foo()"
// A* c = new C; // doesn't compile as expected
}
这段代码定义的好吗?我们可以用纯说明符覆盖定义吗?
[Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. — end note]
甚至 C++11 标准 中也包含完全相同的注释。所以,答案是是的,它是有效的。