c++ - 为什么子类重写虚函数不能改变父类默认函数参数?

标签 c++

我从一本书上读了一些代码,像这样:

#include<iostream>

using namespace std;

class Father
{
public:
    virtual void test(int value=520)
    {
        cout<<"father:"<<value<<endl;
    }
};

class Son :public Father
{
public:
    virtual void test(int value=250)
    {
        cout<<"son:"<<value<<endl;
    }
};

int main()
{
    Son* son =new Son;
    son->test();
    Father* fson= son;
    fson->test();
}

程序输出:

son250

son520

书上说,虚函数的默认参数在编译时确定。

我的问题是: 虚函数的默认参数为什么不在运行时决定?就像虚函数本身。

最佳答案

C 和 C++ 的开发者不想让事情复杂化。实现在编译时解析的默认参数很简单,但在运行时就没那么简单了。但是,您可以而且应该使用一种解决方法。不使用默认参数,而是引入一个没有参数的虚函数。

class Father
{
public:
    virtual void test(int value)
    {
        cout << "father:" << value << endl;
    }


    virtual void test()
    {
        test(520);
    }
};

class Son : public Father
{
public:
    virtual void test(int value)
    {
        cout << "son:" << value << endl;
    }

    virtual void test()
    {
        test(250);
    }
};

关于c++ - 为什么子类重写虚函数不能改变父类默认函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28826246/

相关文章:

c++ - 在 C++ 的功能 ISA 模拟器上实现陷阱(异常/中断)

c++ - unordered_set<int>::iterator it+n 的时间复杂度是多少?

C++ popen() 的输出到一个字符串

c++ - 在 C++ 中使用 libcurl 在 Linux 上使用变量设置绝对路径

c++ - 使用 malloc、char 数组和指针

c++ - 无法解析嵌套枚举

c++ - 处理未知数量的 undefined object 以进行记录

c++ - 求 'n'二进制串中最长公共(public)子串的长度

c++ - SDL 窗口未出现

C++ - 函数总是返回真