知其所以然,C++系列4 - 函数默认参数

一个小练习题,猜猜结果:

#include<iostream>
using namespace std;

enum HEIGHT{
    LOW=150,
    MID=160,
    HIGH=170
};

class Person{
    public:
        virtual void printHeight(int h=LOW){
            cout<<"h in Person="<<h<<endl;
        }
};

class Man: public Person{
    public:
        virtual void printHeight(int h=HIGH) override{
            cout<<"h in Man="<<h<<endl;
        }
};

int main(){
    Man m;
    m.printHeight();  //h in Man=170
    Person *p = &m;
    p->printHeight(); //h in Man=150
}

结果已经在代码注释中。

好像《effective c++》有过解释,标准也有如下话语(也可参考)Default arguments - cppreference.com

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.

意思是:我们知道虚函数调用是动态决定的,但默认参数是静态(编译期)决定的 。哪到底怎么静态决定的哪?默认参数又是怎么传参的哪?调出汇编看一看:

 0xaa就是170,0x96就是150,就是这么直接给传了进去。

大多数人都有个疑问,为啥不像虚函数那样动态决定默认参数?stackoverflow上有同样的问题,如有兴趣请参数c++ - static binding of default parameter - Stack Overflow

 大概意思就是实现起来复杂。可能也不值得,把责任丢给了开发者。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深山老宅

鸡蛋不错的话,要不要激励下母鸡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值