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;      
}

 

你可能感兴趣的:(struct,Class)