多态的简单应用

以下是多态的简单应用:通过父类的纯虚函数来实现多态

#include <iostream>

using namespace std;

class Object
{
public:
    Object()
    {}
    ~Object()
    {}
public:
    virtual void Print()const = 0;
};

class List;

class Listnode
{
    friend class List;
public:
    Listnode(Object *pinfo = NULL) : next(NULL)
    {
        info = pinfo;
    }
    ~Listnode()
    {}
private:
    Object *info;
    Listnode *next;
};

class List
{
public:
    List() : head(NULL), tail(NULL)
    {
        head = tail = new Listnode;
    }
    ~List()
    {}
public:
    void push_back(Listnode *s)
    {
        tail->next = s;
        tail = s;
    }
    void Print()const
    {
        Listnode *p = head->next;
        while(p != NULL){
            p->info->Print();
            p = p->next;
        }
        cout << "Over!" << endl;
    }
private:
    Listnode *head;
    Listnode *tail;
};

class Int : public Object
{
public:
    Int(int x = 0): data(x)
    {}
    ~Int()
    {}
public:
    void Print()const
    {
        cout << data << "-->";
    }
private:
    int data;
};

class String : public Object
{
public:
    String(const char *str) : data(str)
    {}
    ~String(){}
public:
    void Print()const
    {
        cout<<data<<"-->";
    }
private:
    string data;
};

class Char : public Object
{
public:
    Char(char x = 0) : data(x)
    {}
    ~Char()
    {}
public:
    void Print()const
    {
        cout<<data<<"-->";
    }
private:
    char data;
};

int main()
{
    List mylist;
    for(int i = 1; i <= 5; ++i){
        Listnode *s = new Listnode(new Int(i));
        mylist.push_back(s);
    }
    mylist.Print();

    List Strlist;
    Listnode *str = new Listnode(new String("bdef"));
    Strlist.push_back(str);
    str = new Listnode(new String("neyfrhue"));
    Strlist.push_back(str);
    Strlist.Print();

    List charlist;
    for(char i = 'A'; i <= 'Z'; ++i){
        Listnode *s = new Listnode(new Char(i));
        charlist.push_back(s);
    }
    charlist.Print();

    return 0;
}

运行结果:

[root@localhost list]# ./list 
1-->2-->3-->4-->5-->Over!
bdef-->neyfrhue-->Over!
A-->B-->C-->D-->E-->F-->G-->H-->I-->J-->K-->L-->M-->N-->O-->P-->Q-->R-->S-->T-->U-->V-->W-->X-->Y-->Z-->Over!
[root@localhost list]# 

你可能感兴趣的:(多态,纯虚函数)