c++ - 虚函数默认参数行为

我对以下代码有一个奇怪的情况。请帮我澄清一下。

class B
{
       public:
            B();
            virtual void print(int data=10)
            {
                  cout << endl << "B--data=" << data;
            }
};
class D:public B
{
       public:
            D();
            void print(int data=20)
            {
                  cout << endl << "D--data=" << data;
            }
};

int main()
{
     B *bp = new D();
     bp->print();
return 0;
}

关于我期望的输出

[ D--data=20 ]

但实际上是这样的

[ D--data=10 ]

请帮忙。这对你来说似乎很明显,但我不知道内部机制。

最佳答案

标准说 (8.3.6.10):

A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.

这意味着,由于您通过 B 类型的指针调用 print,它使用 B::print 的默认参数。

https://stackoverflow.com/questions/6464404/

相关文章:

c++ - GCC 4.x/C++11 中的 std::string 引用计数了吗?

c++ - 库已链接,但引用未定义

c++ - C++ 标准是否对 float 的表示做了任何规定?

c++ - 析构函数可以是最终的吗?

c++ - 如何在 Windows 上找到 Qt5 CMake 模块

c++ - 如何使用 C++ 模板减少编译时间

c++ - 与 win32 CRITICAL_SECTION 相比的 std::mutex 性能

c++ - 三元表达式中的逗号混淆

c++ - 从基类构造函数调用纯虚函数

c++ - 什么是 C++ 内联类?