C/C++ :C++實函數、虛函數、純虛函數、函數重寫


C++實函數、虛函數、純虛函數、函數重寫


和以前一樣,先做好準備工作。代碼和以前差不多。

首先是父類,People;


頭文件:



#ifndef PEOPLE_H
#define PEOPLE_H

#include<iostream>

using namespace std;

class People{
    public:
        People();//默認是構造方法
        People(int age, int sex);
        int get_age();
        int get_sex();
        void say_hello();

    private:
        int age;
        int sex;
};

#endif // PEOPLE_H

主文件:






#include "People.h"

People::People(){
    this -> age = 18;
    this -> sex = 1;
}//默認的構造方法

People::People(int age, int sex){
    this -> age = age;
    this -> sex = sex;
}


int People::get_age(){
    return this -> age;
}

int People::get_sex(){
    return this -> sex;
}

void People::say_hello(){
    cout << "People: hello world !" << endl;
}

然後是子類Zero:


頭文件:



<span style="font-size:18px;">


#ifndef ZERO_H
#define ZERO_H

#include "People.h"

class Zero:public People{
    public:
        Zero(int age, int sex);
        void say_hello();
};

#endif // ZERO_H
</span>


主文件:




#include "Zero.h"

Zero::Zero(int age, int sex):People(age ,sex){

}


void Zero::say_hello(){
    cout << "Zero: hello world !" << endl;
}


好,現在我們先來隨便寫個main文件:


<span style="font-size:18px;">

#include "Zero.h"

int main()
{
    int a = 20;
    int b = 1;
    People *p = new Zero(a, b);
    p -> say_hello();
    delete p;
    return 0;
}
</span>

我們注意到用People類定義的p指向的是Zero,而我們用p指向的say_hello,是輸出的是People類的呢?

還是Zero類的hello world 呢?


答案是People:helloworld !。。。我們明明指向的是Zero的實例,而輸出的是People類的say_hello;

而這是爲什麼呢?在C++裏, 當我們在子類中將父類中的函數重寫的而且動態的定位到這個方法的話。

這個方法應該是虛函數。。所以,我們在稍微改動一下。

首先是People.h

<span style="font-size:18px;">



#ifndef PEOPLE_H
#define PEOPLE_H

#include<iostream>

using namespace std;

class People{
    public:
        People();//默認是構造方法
        People(int age, int sex);
        int get_age();
        int get_sex();
        virtual void say_hello();

    private:
        int age;
        int sex;
};

#endif // PEOPLE_H
</span>

再是Zero.h


<span style="font-size:18px;">


#ifndef ZERO_H
#define ZERO_H

#include "People.h"

class Zero:public People{
    public:
        Zero(int age, int sex);
        virtual void say_hello();
};

#endif // ZERO_H
</span>


將兩個頭文件中的say_hello方法都以虛函數方式構造。而此時輸出的say_hello,

就是Zero類的“Zero:hello world !”。。這也就是函數的重寫。。



而在C++中,出了虛函數以外,還有一種函數,叫做純虛函數。它呢,主要是在父類中不實現,我們把它在子類中實現。

首先, 我們在People.h中寫入


<span style="font-size:18px;">

        virtual void eat() = 0; //指明爲抽象方法。
</span>


此時,我們運行時,就會報錯了,這時,我們要在Zero.h中寫入它的方法。


<span style="font-size:18px;">


#ifndef ZERO_H
#define ZERO_H

#include "People.h"

class Zero:public People{
    public:
        Zero(int age, int sex);
        virtual void say_hello();
        virtual void eat(){
            cout << "eat: 0" << endl;
        }
};

#endif // ZERO_H
</span>

此時,我們運行,就沒有錯誤了。然後,我們來執行輸出它。


<span style="font-size:18px;">

    p -> eat();</span>

雖然,我們沒有在People類中來實現它,但還是結果順利輸出了。




PS:就算前進的只是一小步,那也是一種進步!












發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章