首页 > 代码库 > struct和class的区别
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的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。