重载,覆盖,隐藏与多态是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;