重载覆盖多态和虚函数

现在整理出来,希望可以记住这个。

重载

函数的名称一样,但是参数不同,就是重载;
函数的名称知道了,但是编译的时候不知道调用哪个函数,重载决议;根据参数决定到底应该调用哪个函数;
区别就是:调用的参数不一样;

覆盖

对于非虚函数,子类和基类同名(不管参数),那么就是导致覆盖;
如果参数完全一样,那么会完全覆盖,只会留下子类的函数;如果参数不一样,那么父类的会保留到子类中;


// =========================================
// 覆盖

#include <iostream>
#include <string>
using namespace std;
class A {
public:
 void print(string &str) {
  cout << str << endl;
 }
 void fun(int a, int b) {
  cout << "A:a+b=" << a + b << endl;
 }
};
class B : public A {
public:
 // B会完全继承A的print函数
 
  // B的fun函数 覆盖了A的fun
 void fun(int a, int b) {
  cout << "B:a*b=" << a*b << endl;
 }
};

int main() {
 A a;
 B b;
 //a 调用A::fun
 a.fun(1, 2);
 // b 调用B::fun
 b.fun(2, 3);
 // a 指定调用A::fun
 b.A::fun(3, 4);
 a.print("1234444");
 b.print("8888888");
  return 0;
}

输出结果:

在这里插入图片描述

多态

通过虚函数实现多态;对于同名函数,基类的指针指向子类的时候,如果是虚函数,会调用子类的函数;

#include <iostream>
#include <string>
using namespace std;
// =====================================
// 多态
class A {
public:
        void print(string str) {
            cout << "调用了A::" << str << endl;
        }

        virtual void fun(int a, int b) {

            cout << "A:a+b=" << a + b << endl;

        }

    };



    class B : public A {

    public:

        void print(string str) {

            cout << "调用了B::" << str << endl;

        }

    

        // B的fun函数 覆盖了A的fun

        virtual void fun(int a, int b) {

            cout << "B:a*b=" << a*b << endl;

        }

    };



    int main() {

        A a;

        B b;

        a.fun(1, 2);

        b.fun(2, 3);

        a.print("1234444");

        b.print("8888888");

        //虚函数调用

        A* p = &a;

        // 此处调用了A::print

        p->print("p->print(str)");

        // 此处调用了A::fun

        p->fun(10, 12);

        p = &b;

        // 此处调用了A::print

        p->print("p->print(str)");

        // 此处调用了B::fun

        p->fun(10, 12);

        return 0;

    }

输出结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值