我基本上從Item 21. Overriding Virtual Functions
複製this example在草本薩特的書Exceptional C++
。標準中是否有支持以下結果的報價?
#include <iostream>
class Base {
public:
virtual void f(int i = 10) { std::cout << i << '\n'; }
};
class Derived : public Base {
public:
void f(int i = 20) { std::cout << i << '\n'; }
};
int main()
{
Base* p = new Derived;
p->f();
}
令人驚訝的(至少對我來說)的代碼打印10(不是20),筆者在第122頁解釋了這個用下面的話:The thing to remember is that, like overloads, default parameters are taken from the static type (here Base) of the object, hence the default value of 10 is taken. However, the function happens to be virtual, so the function actually called is based on the dynamic type (here Derived) of the object.
是否有在C++ 11的任何報價標準支持這個?
可能的複製,請參閱下面的答案: http://stackoverflow.com/questions/3533589/can-virtual-functions-have-default-parameters – vsoftco
香草口吃,真的嗎? –