Private inherit public and protected member of basic class will be regarded as private member in derived class. Member functions of derived class can directly access the public and protected member of basic class,but can't access the private member of basic class. The objects of derived class can't access the any member of basic class. 2017年4月26日星期 第11章继承与派生 0雪2时16分24秒 22 BACK NEXT
HOME2017年4月26日星期 三12时16分24秒 第11章 继承与派生 22 • public and protected member of basic class will be regarded as private member in derived class. • Member functions of derived class can directly access the public and protected member of basic class, but can’t access the private member of basic class. • The objects of derived class can’t access the any member of basic class
例11.2访问私有基类的成员 class Student1:private Student 声明派生类 Student1 天 public: void display_1() cout<<"age:"<<age<<endl; cout<<"address:"<<addr<<endl; private: int age; string addr; 2017年4月26日星期 第11章继承与派生 23 0画2时16分24秒 BACK NEXT
HOME2017年4月26日星期 三12时16分24秒 第11章 继承与派生 23 class Student1: private Student //声明派生类 Student1 { public: void display_1( ) { cout<<"age: "<<age<<endl; cout<<"address: "<<addr<<endl; } private: int age; string addr; };
int main() { Student1 stud1; stud1.display(); /错误 stud1.display_1(); stud1.age=18; /错误 return 0; 2017年4月26日星期 第11章继承与派生 0雪2时16分24秒 24 BACK NEXT
HOME2017年4月26日星期 三12时16分24秒 第11章 继承与派生 24 int main( ) { Student1 stud1; stud1.display(); //错误 stud1.display_1( ); stud1.age=18; //错误 return 0; }
结论 ()不能通过派生类对象(类外)引用从私有 基类继承过来的任何成员 (2)派生类的成员函数不能访问私有基类的私 有成员,但可以访问私有基类的公用成员。 可以通过派生类的成员函数调用私有基类的公 用成员函数,从而引用私有基类的私有成员。 017年4月26日星期 第11章: 继承与派生 2 HOME 12时16分24秒 BACK NEXT
HOME2017年4月26日星期 三12时16分24秒 第11章 继承与派生 25 (1) 不能通过派生类对象(类外)引用从私有 基类继承过来的任何成员。 (2) 派生类的成员函数不能访问私有基类的私 有成员,但可以访问私有基类的公用成员。 可以通过派生类的成员函数调用私有基类的公 用成员函数,从而引用私有基类的私有成员
例11.2改访问私有基类成员 void display_1() displayO); cout<<"age:"<<age<<endl; cout<<"address:"<<addr<<endl;} int main() Student1 stud1; stud1.display_1(); return 0; 私有派生类限制太多,使用不便,一般不使用。 2017年4月26日星期 第11章继承与派生 0雪2时16分24秒 26 BACK NEXT
HOME2017年4月26日星期 三12时16分24秒 第11章 继承与派生 26 void display_1( ) { display(); cout<<"age: "<<age<<endl; cout<<"address: "<<addr<<endl;} int main( ) { Student1 stud1; stud1.display_1( ); return 0; } 私有派生类限制太多,使用不便,一般不使用