方法重载-重写-重定义

重载(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()下的同名方法 (函数名、参数列表、返回类型)完全相同 ,称为方法重写.
  • 可以是任何函数,不要求一定是虚函数,也要求参数列表和基类函数不相同。基类同名函数会被隐藏,称为方法重定义
posted @   NAGISB  阅读(3)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示