C++ 重载 重定义 与重写

  1. 重载:相同行为方法的不同实现
  2. 重定义:基类与派生类之间的 “重载”
  3. 重写:虚函数的 “覆盖”

重载:

同一个 域 内所有的 同名不同参数列表(参数个数,类型,类型顺序;忽略返回值类型)称为一组函数重载

重定义:

派生类对所继承的普通函数的“重载”。

重定义是以 同名函数组 为单位进行的,派生类重载基类一个函数,所有基类同名函数均被隐藏

“隐藏函数” 可以通过subclass_object.Base::fun()方式静态调用

eg:

#include <iostream>
using namespace std;
class Base{
    public:
    void foo(){
        cout<<"(null)"<<endl;
    }
    void foo(int k){
        cout<<"(void)"<<k<<endl;
    }
    void foo(string s){
        cout<<"(string)"<<s<<endl;
    }
};
class Derived :public Base{
    public:
    void foo(char c){
        cout<<"(Derived,char)"<<c<<endl;
    }
};
int main()
{
    Base k {};
    k.foo();
    k.foo(9);
    k.foo("hello");
    //:重定义 foo() 函数
    Derived d ;
    d.foo('u');
    //: Base:: foo()函数组 被重定义隐藏
    // d.foo();
    // d.foo(1);
    // d.foo("123456");
    //:使用静态调用 调用基类被隐藏函数
    d.Base::foo();//:==d.Derived::Base::foo();
    d.Base::foo(-9);//:==d.Derived::Base::foo(-9);
    d.Base::foo("world");//:d.Derived::Base::foo("world");
    return 0;
}
(null)
(void)9
(string)hello
(Derived,char)u
(null)
(void)-9
(string)world

 

 


重写

派生类对所继承的虚函数进行的 覆盖;

重写以个为单位,每次对 同参数列表 同返回值类型 同名方法 进行覆盖。

使用 virtual(必备) 于 override(不必备)关键字结对配合,一次为虚函数,一直为虚函数。

利用虚函数机制的 晚绑定上转型 实现动态调用。

eg:

#include <iostream>
#include <typeinfo>
using namespace std;
class Base{
    public:
    uint64_t a;
    virtual void foo(int k){
        cout<<"(Base::void,int)"<<k<<endl;
    }
    virtual void foo(string s,int k){
        cout<<"(Base::void,string,int)"<<s<<k<<endl;
    }
    virtual void display(){
        cout<<"This is "<<typeid(*this).name()<<endl;
    }
};
class Derived :public Base{
    public:
    // int foo(int k) override{ //!conflicting return type specified for 'virtual int Derived::foo(int)'
    //     cout<<"(Derived::int,void)"<<k<<endl;
    // }
    void foo(int k) { 
        cout<<"(Derived::int,void)"<<k<<endl;
    }
    void foo(string s,int k) override {
        cout<<"(Derived::void,string,int)"<<s<<k<<endl;
    }
    void display() override {
        cout<<"This is "<<typeid(*this).name()<<endl;
    }

};
class test_class{
    uint64_t k;
};
void print(Base &k){
    k.display();
    k.foo("hello world",999);
}
int main()
{
    Base b {};
    Derived d {};
    //:虚函数 类的大小==成员变量大小+指针(虚函数表指针)大小
    cout<<sizeof(b)<<"\t"<<sizeof(d)<<"\t"<<sizeof(test_class)<<endl;
    //:上转型
    print(b);
    print(d);
    return 0;
}
16      16      8
This is 4Base
(Base::void,string,int)hello world999
This is 7Derived
(Derived::void,string,int)hello world999

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值