关于虚函数的继承和const对象及函数重载

#include <iostream>

using namespace std;
struct B
{
    int i;

    virtual const B& f() const
    {
        cout<<"2";
        return *this;
    }
    virtual int f()
    {
        cout<<"1";
        return 1;
    }
    int g()
    {
        cout<<"3";
        return 3;
    }
};
struct D: B
{
    int i;
    int f()
    {
        cout<<"4";
        return 4;
    }
    const B& f() const
    {
        cout<<"5";
        return *this;
    }
    int f(int = 0)
    {
        cout<<"6";
        return 6;
    }
    virtual int g()
    {
        cout<<"7";
        return 7;
    }
};
int main()
{
    D d;
    const D d_const;
    B b,*p = &d;
    const B* p_const = &d_const;
    b.f();//优先调用非const函数
    p->f();//f为虚函数,p由d赋值,执行派生类的f函数
    p->g();//B中g函数不是虚函数,调用基类的g函数
    p_const->f();//const对象只能调用const函数
    d_const.f();
    return 0;
}
输出为:14355
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值