为什么派生类函数自变量采用基类函数自变量的值? [英] Why derived class function argument takes value of base class function argument?

查看:107
本文介绍了为什么派生类函数自变量采用基类函数自变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++.以下是我的代码:

I'm working on C++. Following is my code:

#include <iostream>
using namespace std;
class base
{
        public:
        virtual void display(int a = 4)
        {
                cout << "base ::  "<<  a*a << endl;
        }
};

class derived : public base
{
        public:
        void display(int b = 5)
        {
                cout << " Derived :: " << b*b*b <<  endl;
        }
};

int main()
{
        base *bobj;
        derived dobj;
        bobj = &dobj;
        bobj->display();
        return 0;
}

输出为:

Derived :: 64

调用了基类的函数,但是使用了派生函数的参数的默认值. 为什么派生类方法display()接受基类方法的参数值?

The function of Base class is called, but default value of the parameter of derived function is used. Why the derived class method display(), takes the base class method argument value?

推荐答案

因为您是通过指向base的指针来调用它的.就是这样.

Because you're calling it through a pointer to base. That's how it works.

在实际调用之前 将参数推入参数堆栈(或内部寄存器)中.因为您有一个指向base的指针且没有参数,所以默认的4被传递给该函数.然后,将使用base的默认参数调用正确的函数(derived::display).当然,这是一个实现细节,但是行为是标准的.

Arguments are pushed on the argument stack (or inside registers) before the actual call. Because you have a pointer to base and no parameters, the default 4 is passed to the function. Then the correct function is called (derived::display), but with base's default parameter. Of course, this is an implementation detail, but the behavior is standard.

虚拟函数调用(10.3)在由static确定的虚拟函数的声明中使用默认参数 表示对象的指针或引用的类型.派生类中的重写函数不会获得默认值 覆盖该函数的参数.

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.

我将重点放在报价单上,但整个过程都是不言自明的.

I would provide emphasis on the quote, but the whole thing is pretty self-explanatory.

dobj.display();

将打印125(5 ^ 3).

would print 125 (5^3).

这篇关于为什么派生类函数自变量采用基类函数自变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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