C++的重载,重写(覆盖),重定义(隐藏)详解

1.重载
在一个类中,用一样的函数名,不同的函数参数或函数类型(但不能是不同的返回类型)写的几个方法称为函数的重载;
举个栗子:

class Test{
    public:
        int sum(int a,int b)
        {
            return a+b;
        }
        double sum(double a,double b)
        {
            return a+b;
        }
};
int main()
{
    Test test;
    int a,b;
    double x,y;
    cout<<test.sum(a,b)<<test. sum(x,y)<<endl;
    return 0;
}

如上所示,sum自动匹配不同函数类型的方法。
2.重写
覆盖:一般是父类和子类的方法一模一样(函数名,函数类型,参数列表),一般重写的标志就是virtual。注意static声明的方法不能重写
再举个栗子:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
class AA{
    public:
        virtual void print(int x)
        {
            cout<<"父类:"<<x<<endl; 
        }
};
class BB:public AA{
    public:
        virtual void print(int x)
        {
            cout<<"子类"<<x<<endl; 
        }
};
int main()
{ 
    AA a;
    BB b;
    AA *p=&a;
    p->print(1);
    p=&b;
    p->print(2);
    return 0;
}

输出为:父类:1
子类2

重写比较好理解,也就是如果你指向子类的对象那么,就执行子类的方法(子类覆盖父类),如果指向父类的对象,就执行父类的方法。

3.重定义
子类重新定义父类中有相同名称的非虚函数 ( 参数列表可以不同 )
通过子类的对象也可以访问父类,格式为:b.AA:print();
子类对象.父类类名::重定义方法;

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
class AA{
    public:
        void print()
        {
            cout<<"hello"<<endl;
        }

};
class BB :public AA{
    public:
        void print()
        {
            cout<<"helloworld"<<endl; 
        }
};
int main()
{
    AA a;//父类 
    BB b;//子类 
    b.print();//访问子类的print 
    a.print();//访问父类的print 
    b.AA::print();//通过子类的对象访问父类的print 
    return 0;
}

输出:

helloworld
hello
hello

猜你喜欢

转载自blog.csdn.net/csustudent007/article/details/80331143