虚函数默认参数 [英] Virtual functions default parameters
本文介绍了虚函数默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以解释c ++编译器保留虚函数参数的默认值吗?我知道这是一个坏主意,在儿童类中更改这些参数,但为什么?
谢谢。
Could anybody explain where c++ compilers keep default values for parameters for virtual functions? I know it is a bad idea to change these parameters in child classes but why? Thanks.
推荐答案
这是一个坏主意,因为它们不会保存在任何地方。
It's a bad idea because they aren't kept anywhere.
所使用的默认值将是在静态(编译时)类型中定义的值。因此,如果您要更改覆盖中的默认参数,但是您通过基类指针或引用调用该函数,则将使用基础中的默认值。
The default values that are used will be those defined in the static (compile-time) type. So if you were to change the default parameters in an override, but you called the function through a base class pointer or reference, the default values in the base would be used.
#include <iostream>
struct Base
{
virtual ~Base(){ }
virtual void foo(int a=0) { std::cout << "base: " << a << std::endl; }
};
struct Derived : public Base
{
virtual ~Derived() { }
virtual void foo(int a=1) { std::cout << "derived: " << a << std::endl; }
};
int main()
{
Base* derived = new Derived();
derived->foo(); // prints "derived: 0"
delete derived;
}
这篇关于虚函数默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文