标签:
之前一直以为c++中有class的原因是c中的struct不能有构造函数,析构函数,继承等功能,没想到struct也可以实现这些功能。
只不过class中默认的关键字是private,而struct中默认的关键字是public。
以一个例子来说明用struct实现类的一些功能。
eg:
#include <iostream>
using namespace std;
enum BREED {GOLDEN,CAIRN,DANDIE,SHETLAND,DOBERMAN,LAB};//BREED是一种数据类型了,其值可以是括号里的任意一个,第一个默认为0
struct Mammal
{
protected:
int itsAge;
int itsWeight;
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 << "\n Mammal sound! \n"; }
void Sleep() const { cout << "\n Shhh.I‘m sleeping"; }
};
struct Dog :public Mammal
{
private:
BREED itsBreed;
public:
Dog() :itsBreed(GOLDEN){}
~Dog(){}
BREED getBreed() const { return itsBreed; }
void SetBreed(BREED breed){ itsBreed = breed; }
void WagTail() const { cout << "Tail wagging...\n"; }
void BegForFood() const { cout << "Begging for food...\n"; }
};
int main()
{
Dog fido;
fido.Speak();
fido.WagTail();
cout << "Fido is " << fido.GetAge() << "years old \n";
return 0;
}
输出为:Mammal sound!
Tail wagging...
Fido is 2years old
标签:
原文地址:http://www.cnblogs.com/xh0102/p/5203371.html