1. 程式人生 > >多型例項

多型例項

#include <iostream>
#include <string>
#include <vector>

using namespace std;


struct Base
{
    string baseName;
};

struct SubA : public Base
{
    string subName_A;
};

struct SubB : public Base
{
    string subName_B;
};

//by zhaocl
int main()
{
    //init
    Base * base;
    base->baseName = "baseName";

    A a;
    B b;
    a.baseName = "baseA";
    a.subName_A = "subA";
    b.baseName = "baseB";
    b.subName_B = "subB";
    
    //此時只能訪問基類成員
    base = &a;
    cout << base->baseName << endl;
    base = &b;
    cout << base->baseName << endl;
    
    //訪問所有成員
    cout << ((SubA*)base)->baseName << endl;
    cout << ((SubA*)base)->subName_A << endl;
    return 0;
}

說明:

1、struct和class的區別這裡就不贅述了,同理class

擴充套件:

1、實際應用:有多個檔案存在,他們有共同的屬性,也有不同的屬性。為了便於區分和管理,我們需要設計一個合理的類結構。比如一個基類,其中包含共有屬性,每個檔案是它的子類,包含各自的屬性,而不是每個檔案一個單獨的類。這樣,我們操作共同屬性時,可以定義一個基類指標就可以了,而不是分別定義多個類。