C ++多态性和默认参数 [英] C++ polymorphism and default argument

查看:61
本文介绍了C ++多态性和默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些课程:

class Base
{
    public:
        virtual void foo(int x = 0)
        {
            printf("X = %d", x);
        }
};

class Derived : public Base
{
    public:
        virtual void foo(int x = 1)
        {
            printf("X = %d", x);
        }
};

当我有:

Base* bar = new Derived();
bar->foo();

即使从Derived调用了foo,我的输出也是"X = 0",但是当我有以下情况时:

My output is "X = 0", even if foo is called from Derived, but when I have:

Derived* bar = new Derived();
bar->foo();

我的输出是"X = 1".这种行为正确吗?(要从声明类型中选择默认参数值,而不是从实际对象类型中选择它).这会打破C ++多态性吗?

My output is "X = 1". Is this behavior correct? (To select default parameter value from the declaration type, instead of selecting it from actual object type). Does this break C++ polymorphism?

如果有人使用虚函数而不指定实际的函数参数并使用函数的默认参数,则会导致很多问题.

It can cause many problems if somebody uses virtual functions without specifying the actual function parameter and uses the function's default parameter.

推荐答案

即使覆盖函数,默认参数也会保留!而且这种行为是正确的.让我从C ++标准中搜索参考.

Default arguments are retained even if you override a function! And this behaviour is correct. Let me search the reference from the C++ Standard.

§8.3.6/10(来自C ++标准的[默认参数])

§8.3.6/10 [Default arguments] from the C++ Standard says,

虚拟函数调用(10.3)使用中的默认参数虚函数的声明由静态类型决定表示对象.派生类不获取默认值来自函数的参数覆盖.

来自标准本身的示例

struct A {
     virtual void f(int a = 7);
};
struct B : public A {
     void f(int a);
};
void m()
{
    B* pb = new B;
    A* pa = pb;
    pa->f(); //OK, calls pa->B::f(7)
    pb->f(); //error: wrong number of arguments for B::f()
}

不仅保留它,而且每次调用该函数时都会对其进行评估:

Also, not only it's retained, it is evaluated everytime the function is called:

§8.3.6/9说,

分别评估默认参数该函数被调用的时间

Default arguments are evaluated each time the function is called

这篇关于C ++多态性和默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆