1. 程式人生 > 實用技巧 >C++基礎-類的繼承

C++基礎-類的繼承

類的繼承: 當使用class Pig:public Animal{} 就可以繼承Animal裡面的屬性,

類的函式改寫: 對於繼承父類的屬性,可以在子類裡面重新被定義和改寫

#include <iostream>

class Animal{
public:
    std::string mouth;

    Animal();
    ~Animal();
    void eat();
    void sleep();
    void drool();
};

Animal::Animal() {
    std::cout << "請開始你的表演" << std::endl;
}

Animal::
~Animal() { std::cout << "遊戲結束" << std::endl; } void Animal::eat() { std::cout << "正在吃飯" << std::endl; } void Animal::sleep() { std::cout << "我正在吃飯" << std::endl; } void Animal::drool() { std::cout << "我正在流口水" << std::endl; } class
Pig : public Animal { public: void eat(); void climb(); }; void Pig::climb() { std::cout << "我是豬我會爬樹" << std::endl; } void Pig::eat() { std::cout << "豬正在吃飯" << std::endl; } class Turble : public Animal { public: void eat(); void swim(); }; void Turble::swim() { std::cout
<< "小烏龜正在游泳" << std::endl; } void Turble::eat() { std::cout << "小烏龜正在吃飯" << std::endl; } int main() { Turble turble; Pig pig; turble.eat(); turble.swim(); pig.eat(); pig.climb(); }