方法重载-重写-重定义
重载(Overloading
允许在同个作用域中的某个函数
根据形参指定多个定义,分别称为方法重载非多态性 
/* C++:方法重载 */
#include <iostream>
using namespace std;
class printData {
    public:
        void print(int i) {
            cout << "整数为:" << i << endl;
        }
        void print(double f) {
            cout << "浮点数为:" << f << endl;
        }
        void print(char c[]) {
            cout << "字符串为:" << c << endl;
        }
};
int main()
{
    printData pd;
    pd.print(5); //重载1
    pd.print(500.263); //重载2
    char c[] = "Nagisb";
    pd.print(c); //重载3
    return 0;
}
重写(Overriding
通过基类指针或引用调用该基类函数, (也叫覆盖), 可添加
新特性新实现多态性 
/* C++:方法重写 */
#include <iostream>
using namespace std;
// 基类
class printData {
public:
    // 基类构造函数
    printData() {
        cout << "基类构造函数被调用" << endl;
    }
    void print(int i) {
        cout << "整数为:" << i << endl;
    }
    void print(double f) {
        cout << "浮点数为:" << f << endl;
    }
    void print(char c[]) {
        cout << "字符串为:" << c << endl;
    }
};
// 派生类
class derivedPrintData : public printData {
public:
    // 派生类构造函数,引用基类构造函数, 方便重写
    derivedPrintData() : printData() {
        cout << "派生类重写的构造函数被调用" << endl;
    }
};
int main()
{
    // 创建派生类对象
    derivedPrintData dpd;
    dpd.print(5); // 调用基类的print(int)
    dpd.print(500.263); // 调用基类的print(double)
    char c[] = "Nagisb";
    dpd.print(c); // 调用基类的print(char[])
    return 0;
}
重定义(Hiding
通过定义同名不同参的方法,基类的同名方法会被派生类的方法隐藏
非多态性 
// 基类
class Base {
public:
    void func() {
        std::cout << "Base::func()" << std::endl;
    }
};
// 派生类
class Derived : public Base {
public:
    void func(int x) {
        std::cout << "Derived::func(int): " << x << std::endl;
    }
};
非多态性
- 编辑器通过方法的(参数类型和定义中的参数类型)(参数个数、类型或者顺序)进行
比较,决定适合的定义,称为重载决策. - 在派生类的
重写方法下,再次引用基类super()下的同名方法 (函数名、参数列表、返回类型)完全相同,称为方法重写. - 可以是任何函数,不要求一定是虚函数,也要求参数列表和基类函数
不相同。基类同名函数会被隐藏,称为方法重定义 

                
            
        
浙公网安备 33010602011771号