|
父类
class People {
public:
People(char *str); //构造函数
~People(); //析构函数
protected:
char *name;
};
#endif
父类实现:
{
People::People(char *str) {
name = new char[strlen(str)+1];
strcpy(name, str);
cout<<"People construct: "<<name<<endl;
}
//析构函数的实现
People::~People() {
cout<<"People destroy: "<<name<<endl;
delete []name;
}People::People(char *str) {
name = new char[strlen(str)+1];
strcpy(name, str);
cout<<"People construct: "<<name<<endl;
}
//析构函数的实现
People::~People() {
cout<<"People destroy: "<<name<<endl;
delete []name;
}
派生类:
class Teacher : public People {
public:
Teacher(char *str, char *sch); //构造函数
~Teacher(); //析构函数
protected:
char *school;
};
派生实现
Teacher::Teacher(char *str, char *sch)
:People(str) //调用基类的构造函数
{ school = new char[strlen(sch)+1];
strcpy(school,sch);
cout<<"Teacher construct: "<<name<<" in "------1
<<school<<endl;
}
Teacher::~Teacher() {
cout<<"Teacher destroy: "<<name<<" in "-----------2
<<school<<endl;
delete []school; }
父类成员name必须为保护类型,才能在派生类的构造,析构函数中 1,2处 用到name。改为私有类型,子类中就无法访问。 但是子类继承时也有自己的name属性 继承过来,为什么不能调用, 1,2处调用的name是父类的还是子类的?
|
|