struct和class的區別

class中變量默認是private,struct中的變量默認是public,其他兩個均相似,可以有構造函數析構函數,也可以繼承。

#include <iostream>
using namespace std;
enum BREED {GOLDEN,CAIRN,DANDIE,SHETLAND,DOBERMAN,LAB};
struct Mammal
{
    public:
        Mammal():itsAge(2),itsWeight(5){}
        ~Mammal() {}

        int GetAge() const {return itsAge;}
        void SetAge(int age) {itsAge = age;}
        int GetWeight() const {return itsWeight;}
        void SetWeight(int weight) {itsWeight = weight;}

        void Speak() const {cout<<"\nMammal sound!";}
        void Sleep() const {cout<<"\nShhh.I'm sleeping.";}
    protected:
        int itsAgel;
        int itsWeight;               
}; 
struct Dog:public Mammal
{
    public:
        Dog():itsBreed(GOLDEN){}
        ~Dog(){}
        BREED GetBreed() const {return itsBreed;}
        void SetBreed(BREED breed) {itsBread = breed;}
        void WagTail() const {cout<<"Tail wagging...\n";}
        void BegForFood() const {cout<<"Begging for food...\n";}
    private:
        BREED itsBreed;       
};
int main()
{
    Dog fido;
    fido.Speak();
    fido.WagTail();
    cout<<"Fido is"<<fido.GetAge()<<"years old \n";
    return 0;      
}

 

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