先编写程序:
#include <iostream>
using namespace std;
class Animal
{
protected:
float weight;
public:
void setWeight(float w)
{
weight = w;
}
float getWeight()
{
return weight;
}
void breathe()
{
cout << "breathing..." << endl;
}
};
class Dog : public Animal
{
private:
int legs;
public:
void setLegs(int number)
{
legs = number;
}
int getLegs()
{
return legs;
}
void bark()
{
cout << "wang! wang!" << endl;
}
};
int main(int argc, char** argv)
{
Dog dog;
dog.setWeight(12.5);
dog.setLegs(4);
cout << "The dog's weight is " << dog.getWeight() << "kg" << endl;
cout << "The dog has " << dog.getLegs() << " legs" << endl;
dog.breathe();
dog.bark();
return 0;
}
运行结果:
The dog’s weight is 12.5kg
The dog has 4 legs
breathing...
wang! wang!
程序分析:
(1)Animal为一个类,Dog为另一个类。
class Dog : public Animal 表示Dog类继承了 Animal类。此时,Animal就成了Dog的基类或父类。Dog就成了Animal的派生类或子类。
(2)体重和呼吸是所有动物的共性,所以weight和breathe()定义在类Animal中。腿和吠不是所有动物的共性,所以legs和bark()定义在了类Dog中。
(3)class Dog : public Animal , 这里的public表示继承方式 。
继承方式有三种:public, protected和private。
① 父类为private的属性和方法,不能被子类继承。
② 父类为protected的成员,若被子类public继承的,仍为子类的protected成员;若被子类protected或private继承的,变为子类的private成员。
③ 父类为public的成员,若被子类public继承的,仍为子类的public成员;若被子类protected继承的,变为子类的protected成员;若被子类private继承的,变为子类的private成员。
注:这些不用强记,编多了自然就知道
(4)根据(3)中第③条的结论,若程序改为class Dog : protected Animal,则程序无法通过编译。因为setWeight()和getWeight()被protected继承后,变为Dog的protected成员,而protected成员,无法在类外部(比如main函数中)访问。
更多内容请关注微信公众号