[英]C++ Polymorphism: Does a virtual function in derived class needs to be declared constant if its declared constant in base class
I have two classes. 我有两节课。 In base class A virtual function
window(void)
is declared constant const
while in derived class B, window(void)
is not declared as cont
. 在基类A中,虚函数
window(void)
声明为常量const
而在派生类B中, window(void)
不声明为cont
。 Does this satisfy polymorphism? 这满足多态性吗? If I call
window()
in main, will it first call the derived class B window()
first and then class A version of window()
. 如果我在main中调用
window()
,它将首先调用派生的B类window()
,然后调用A类版本的window()
。 In my case it's not doing like this. 就我而言,它不是这样。 Should I have to put const at the end of function in derived too?
我是否也必须将const放在派生函数的末尾?
class A
{
public:
virtual int window (void) const
{
std::cout<<" We are in class A "<<std::endl;
return std::min(x,y); // x is smaller
}
private:
int x, y;
}
class B : public A
{
public:
virtual int window (void)
{
std::cout<<" We are in class B "<<std::endl;
return A::window ();
}
}
void main()
{
int z = window();
std::cout<<z<<std::endl;
}
The output should be like this 输出应该是这样的
We are in class B
We are in class A
x
The signature of an overriding method must exactly match the signature of the virtual base method that it is overriding (well, except for the case of covariant return values, but that is not relevant to your question). 覆盖方法的签名必须与要覆盖的虚拟基本方法的签名完全匹配(很好,除了协变返回值的情况外,但这与您的问题无关)。 That signature includes trailing
const
ness. 该签名包括结尾
const
。 So yes, if the base method is declared as const
, the overriding method must be declared as const
as well. 所以是的,如果将基本方法声明为
const
,则也必须将覆盖方法声明为const
。
If you are using C++11 or later, you should mark an overriding method with the override
specifier , then the compiler will validate that it is actually overriding a virtual base method of matching signature , and will generate an error if a matching base method is not found. 如果使用的是C ++ 11或更高版本,则应使用
override
specifier标记一个覆盖方法,然后编译器将验证它实际上是覆盖匹配签名的虚拟基方法,如果匹配基方法,则将生成错误。找不到。 You don't get that validation at compile-time if you omit the override
specifier. 如果忽略
override
指定符,则在编译时不会获得该验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.