#include <iostream> using namespace std; /*类的继承: 派生类,可根据访问限定符(public,private,protected)访问基类的属性和方法 * 使用继承的方式,可以抽象多个对象公共部分,并复用代码 */ class Person { public: //1: public权限,可被派生类访问 bool man; void CheckPerson(); Person() { cout << "Person constructor" << endl; } ~Person() { cout << "~Person deconstructor" << endl; } }; void Person::CheckPerson() { if (man) cout << "Person is man" << endl; else cout << "Person is woman" << endl; } class Man: public Person{ //2: public继承,可访问基类public和protected权限的成员 public: Man() { //构造和析构函数若为private权限,编译错误。默认为private man = true; //3: 派生类为基类的public数值复制 }; ~Man() {}; }; int main() { Man Tom; Tom.CheckPerson(); //4:派生类外部可调用继承的基类public成员 Tom.man = false; //外部可修改继承的public成员 Tom.CheckPerson(); r
output:
Person constructor
Person is man
Person is woman
~Person deconstructor
------------------------------------------------------------------------------------------------
上面代码存在缺陷,Person的man成员,可以在main()函数里面被修改,如果我们不想man在对象外部被改动,仅仅想在派生类中对此成员进行改动,可以使用访问限定符protected对基类进行优化.
#include <iostream>
using namespace std;
/*类的继承: 派生类,可根据访问限定符(public,private,protected)访问基类的属性和方法
* 使用继承的方式,可以抽象多个对象公共部分,并复用代码
*/
class Person {
protected: //1: protected权限,仅可在派生类访问, 不可在对象外部被访问
bool man;
public: //2: public权限,可被派生类访问,也可在派生类对象外部访问
void CheckPerson();
Person() {
cout << "Person constructor" << endl;
}
~Person() {
cout << "~Person deconstructor" << endl;
}
};
void Person::CheckPerson() {
if (man)
cout << "Person is man" << endl;
else
cout << "Person is woman" << endl;
}
class Man: public Person{ //public继承,可访问基类public和protected权限的成员
public:
Man() { //构造和析构函数若为private权限,编译错误。默认为private
man = true; //派生类为基类的public数值复制
};
~Man() {};
};
int main()
{
Man Tom;
//Tom.man = false; //编译失败,继承基类的protected成员,不可在对象外部被访问
Tom.CheckPerson(); //派生类外部可调用继承的基类public成员函数
return 0;
}
output:
Person constructor
Person is man
~Person deconstructor