继承
一个类是另一个类的一种(a kind of)
class People
{
public:
void eat(string foot)
{
cout << "eat:" << foot << endl;
}
void sleep()
{
cout << "sleep" << endl;
}
private:
};
class Student:public People
{
public:
void learn()
{
cout << "learn" << endl;
}
private:
};
int main()
{
Student st;
st.eat("红烧肉");
return 0;
}
派生类中从基类中继承来的成员的访问限定
基类 |
派生类 |
类外 |
public |
public |
可访问 |
protected |
protected |
不可访问 |
private |
不可访问 |
不可访问 |
基类 |
派生类 |
类外 |
public |
protected |
不可访问 |
protected |
protected |
不可访问 |
private |
不可访问 |
不可访问 |
基类 |
派生类 |
类外 |
public |
private |
不可访问 |
protected |
private |
不可访问 |
private |
不可访问 |
不可访问 |
派生类怎么初始化从基类继承来的成员
class People
{
public:
People(int m):ma(m){
cout << "People()" << endl; }
~People(){
cout << " ~People()" << endl; }
void eat(string foot) {
cout << "eat:" << foot << endl; }
void sleep() {
cout << "sleep" << endl; }
private:
int ma;
};
class Student:public People
{
public:
Student(int m):People(m)
{
cout << "Student()" << endl; }
~Student(){
cout << "~Student" << endl; }
void learn() {
cout << "learn" << endl; }
private