C++中的重载,覆盖,隐藏与多态

重载,覆盖,隐藏与多态是C++中面向对象设计的几大特性.深入理解这些特性,对于我们编写高效的可复用,可重用的代码有重要意义.这里,对这一部分知识加以回顾.

重载发生在同一个类当中,当有同名函数,但函数参数不同时,就发生函数的重载.
覆盖发生在基类与派生类当中,基类函数必须是虚函数,派生类又重新实现了基类函数,派生类则对基类同名函数发生覆盖.
隐藏发生在基类与派生类当中,基类函数在派生类中有同名函数,在不构成覆盖的条件的情况下,基类函数均被隐藏.此种情况下,如果想在派生类中调用基类函数,可以通过作用于运算符::来实现.

以下代码解释了上述说明. 另外,代码中也对指针与对象的大小进行了分析. 特别指出的是,派生类对象会全部包含基类的所有成员变量,即使这个成员变量被定义为基类私有的,派生类仍然将为其分配内存空间.但是在派生类中不可见.

程序运行结果如下图:
这里写图片描述

#pragma once
class Basic
{
public:
    virtual void basicPrint1();
    void basicPrint2();
    void basicPrint2(int k);
protected:
    unsigned int i;
private:
    unsigned int k;
};

class Derived : public Basic
{
public:
    void basicPrint1();
    void basicPrint2();
private:
    unsigned int i;
    unsigned int k;
};
#include "Test.h"
#include <iostream>
using namespace std;


void Basic::basicPrint1()
{
    cout << "This is the basic Print1 in basic class" << endl;
}

void Basic::basicPrint2()
{
    cout << "This is the basic Print2 in basic class" << endl;
}

void Basic::basicPrint2(int k)
{
    cout << "This is the overload basic Print2 in basic class, K=" << k << endl;
}



void Derived::basicPrint1()
{
    cout << "This is the basic print1 in derived class, as it is virtual, it is polymorphic" << endl;
}

void Derived::basicPrint2()
{
    //Basic::basicPrint2(44);
    cout << "This is the basic print2 in derived class. It will hide (not overload) the 2 method in basic class with same name." << endl;
}
    Basic *basic = new Basic();
    basic->basicPrint1();
    basic->basicPrint2();
    basic->basicPrint2(22);

    Basic *derivedWithPolymeric = new Derived();
    derivedWithPolymeric->basicPrint1();           //For virtual func, it will go to the drived class
    derivedWithPolymeric->basicPrint2();           //For non virtual func, it still call the basic class
    derivedWithPolymeric->basicPrint2(33);

    Derived *derived = new Derived();
    derived->basicPrint1();
    derived->basicPrint2();   //Only could call the derived class basicPrint2, the basic class same name function is hide

    Basic basic2;
    Derived derived2;

    cout << "The size of basic is : " << sizeof(basic) << endl;
    cout << "The size of derivedWithPolymeric is: " << sizeof(derivedWithPolymeric) << endl;
    cout << "The size of derived is: " << sizeof(derived) << endl;
    cout << "The size of basic2 is :" << sizeof(basic2) << endl;
    cout << "The size of derived2 is :" << sizeof(derived2) << endl;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值