C++中重载,重写,隐藏的区别

重载:

重载是指在同一个作用域下,函数的函数名相同,但是函数参数的个数,或者参数的类型,参数的顺序不同。这时函数之间就构成了重载关系,这里需要注意的是,如果函数的参数列表完全相同,仅仅是返回值类型不同并不能构成重载。同一个作用域又怎么理解呢?在这里主要分两种情况讨论,一种是在类外但是函数在同一个CPP文件中属于同一个作用域,另一种是在类中也属于同一个作用域

函数在类外,但是同在一个CPP文件

//函数在类外,但是同在一个CPP文件

#include <iostream>
using namespace std;

void test(int i)    //函数1
{
    cout << "int" << endl;
}

void test(double i)    //与函数1参数个数相同,参数类型不同,构成重载
{
    cout << "double" << endl;
}

void test(int i, int j)    //与函数1参数类型相同,但是参数个数不同,构成重载
{
    cout << "int int" << endl;
}

int test(int i)    //仅返回值类型不同,不能构成重载
{
    cout << "return int" << endl;
}

函数在类内,这里有一种情况下也可以构成重载,函数名,参数列表完全相同,但是函数有const关键字修饰

//函数在同一个类中

#include <iostream>
using namespace std;

class A
{
public:
    A(){}
    ~A(){};

    void test(int i) //函数1
    {
        cout << "int" << endl;
    }
    void test(double i)//与函数1参数个数相同,参数类型不同,构成重载
    {
        cout << "double" << endl;
    }
    void test(int i, int j)//与函数1参数类型相同,但是参数个数不同,构成重载
    {
        cout << "int int" << endl;
    }
    void test(int i) const //与函数1参数类型参数个数相同,有const 关键字修饰,构成重载
    {
        cout << "const int" << endl;
    }
};

重写(覆盖):

重写也叫做覆盖,发生在父类和子类中,当父类中有虚函数时,在子类中重新定义一个与父类虚函数函数名,函数参数列表一模一样的函数,并重写函数的具体实现,此种情况就构成了重写。

//重写

#include <iostream>
using namespace std;

class A
{
public:
    A(){}
    ~A(){};
    virtual void test()
    {
        cout << "A::test()" << endl;
    }
};

class B :public A
{
public:
    B(){}
    ~B(){}
    virtual void test()//virtual关键字可写可不写
    {
        cout << "B::test()" << endl;
    }
};

隐藏:

隐藏也发生在父类和子类中,主要包含两种情况:

1、子类和父类的函数名,参数类型完全相同,但是父类函数没有virtual关键字修饰

2、子类和父类函数名相同,但是参数列表不同,此时不管有没有virtual关键字修饰,都能构成隐藏

//子类和父类的函数名,参数类型完全相同,但是父类函数没有virtual关键字修饰

#include <iostream>
using namespace std;

class A
{
public:
    A(){}
    ~A(){};
    void test()
    {
        cout << "A::test()" << endl;
    }
};

class B :public A
{
public:
    B(){}
    ~B(){}
    void test()
    {
        cout << "B::test()" << endl;
    }
};
//子类和父类函数名相同,但是参数列表不同,此时不管有没有virtual关键字修饰,都能构成隐藏

#include <iostream>
using namespace std;

class A
{
public:
    A(){}
    ~A(){};
    void test(int i)
    {
        cout << "A::test()" << endl;
    }
};

class B :public A
{
public:
    B(){}
    ~B(){}
    void test()
    {
        cout << "B::test()" << endl;
    }
};//  父类的 test函数需要传入一个int类型的参数,子类的test参数不需要传入任何参数,此时若有如下语句://  B b;//  b.test(1);  //报错//  因为子类中的 void test() 函数已经把父类中的  void test(int i)  函数隐藏,这种方式下子类对象 b 并访问不到 void test(int i),此时可通过 b.A::test(1) 这种方式访问

原文链接: https://www.cnblogs.com/418ks/p/7372608.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/258461

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午11:48
下一篇 2023年2月14日 上午11:48

相关推荐