编程语言
首页 > 编程语言> > c++继承关系中成员函数的重载、重写、重定义之间的区别

c++继承关系中成员函数的重载、重写、重定义之间的区别

作者:互联网

1、Override、Overload、Redefine


2、三者之间的区别

举个例子说明一下:

class Base{
public:
    int param3 = 0;
    void func1(){cout<<"This is Base::func1()"<<endl;}
    void func2(int a){cout<<"This is Base::func2(int a)"<<endl;}
    void func2(char c){cout<<"This is Base::func2(char c)"<<endl;}
    void func3(){cout<<"This is Base::func3()"<<endl;}
    virtual void func4(){cout<<"This is Base::func4()"<<endl;}
    virtual void func5(){cout<<"This is Base::func5()"<<endl;}
    virtual int func6(){cout<<"This is int Base::func6()"<<endl;}
};

class Son: public Base
{
public:
    int param = 1;
    int func1(){cout<<"This is Son::func1()"<<endl;}
    void func2(double e){cout<<"This is Son::func2()"<<endl;}
    void func3(){cout<<"This is Son::func3()"<<endl;}
    void func4(){cout<<"This is Son::func4()"<<endl;}
    void func5(int a){cout<<"This is Son::func5(int a)"<<endl;}
//    double func6(){cout<<"This is Son::func6()"<<endl;}
};

int main() {
    Son s;
    Base b;
    Base *bp = new Son();
    s.func1();
    s.func2(1.1);
    s.func2('c');
    s.func4();
    s.func5(2);
    cout<<"--------------------------------"<<endl;
    b.func1();
    b.func2(1);
    b.func2('c');
    b.func3();
    cout<<"--------------------------------"<<endl;
    bp->func1();
    bp->func2(1);
    bp->func2('e');
    bp->func3();
    bp->func4();
    bp->func5();
    return 0;
}

输出如下:

This is Son::func1()
This is Son::func2()
This is Son::func2()
This is Son::func4()
This is Son::func5(int a)
\--------------------------------
This is Base::func1()
This is Base::func2(int a)
This is Base::func2(char c)
This is Base::func3()
\--------------------------------
This is Base::func1()
This is Base::func2(int a)
This is Base::func2(char c)
This is Base::func3()
This is Son::func4()
This is Base::func5()

分别创建子类、父类、指针类型为父类指向子类空间的指针。(1)父类中的func2发生重载,主要在父类内部产生(应该说相同作用域),因为给s.func2('c')传入字符的时候,只会调用子类函数,不会调用父类的func2(char c)。而子类中的func2对父类的func2发生了重定义,并对其做了隐藏,所以调用的时候才会调用到子类的func2(double )。从s.func1()s.func2()s.func3()都发生了重定义,所以在继承的过程中,如果没有virtual关键字,只要函数名相同,不管参数类型、返回值类型,都会发生重定义。(2)针对有virtual关键字的情况,在函数名相同的情况下,首先要保证返回值类型相同,否则编译不过,如果参数列表相同,则发生重写,不同则发生重定义,例如bp->func4()bp->func5(),这里bp调用函数的处理取决于是否重写的函数(虚函数的特性)。


参考文献

标签:func2,函数,子类,c++,virtual,重载,父类,重写
来源: https://www.cnblogs.com/seasons2021/p/14477537.html