访问方式与继承的特点:
1、类中的protected和private成员,类对象不可显示调用,子类的成员可以调用父类protected成员,但是不能调用private成员。
2、父类中的protected成员被子类以public方式继承后,化为protected成员。
3、父类中的protected成员被子类以protected方式继承后,化为private成员(不常用)。
1、类中的protected和private成员,类对象不可显示调用,子类的成员可以调用父类protected成员,但是不能调用private成员。
2、父类中的protected成员被子类以public方式继承后,化为protected成员。
3、父类中的protected成员被子类以protected方式继承后,化为private成员(不常用)。
继承方式的表格:
基类的访问特性 | 类的继承特性 | 子类的访问特性 |
public protected private | public | public protected NO access |
public protected private | proctected | protected protected NO access |
public protected private | private | private private NO access |
1、对象不可
显示调用protected成员和private成员。
class Animal
{
public:
void eat()
{cout<<"animal eat"<<endl;}
protected:
void sleep()
{cout<<"animal sleep"<<endl;}
private:
void breathe()
{cout<<"animal breathe"<<endl;}
};
int main()
{
Animal an;
an.eat();
an.sleep();//外部不可以调用
an.breathe();//外部不可以调用
return 1;
}
2、子类的成员函数中可以调用父类的protected成员
class Animal
{
public:
void eat()
{cout<<"animal eat"<<endl;}
protected:
void sleep()
{cout<<"animal sleep"<<endl;}
private:
void breathe()
{cout<<"animal breathe"<<endl;}
};
class Fish: public Animal//派生类(子类):基类(父类) 注意继承方式为公有继承
{
public:
void test()
{
eat();
sleep();//子类调用父类中的成员函数(可调用)
breathe();//调用失败
}
};
int main()
{
Fish fh;
fh.test();
fh.eat();
//fh.sleep();//protected外部不可调用
//fh.breathe();//private外部不可调用
return 1;
}
3、
构造函数释放顺序为:从父类到子类;析构函数释放顺序为:从子类到父类
class Animal
{
public:
Animal(int a,int b)
{cout<<"animal construct"<<endl;}
~Animal()
{cout<<"animal deconstruct"<<endl;}
void eat()
{cout<<"animal eat"<<endl;}
void sleep()
{cout<<"animal sleep"<<endl;}
void breathe()
{cout<<"animal breathe"<<endl;}
};
class Fish:public Animal
{
public:
Fish():Animal(400,300),a(1)//XXX:向基类传递参数,对a初始化为1
{cout<<"fish construct"<<endl;}
~Fish()
{cout<<"fish deconstruct"<<endl;}
private:
const int a;//对常量初始化
};
int main()
{
Fish fh;
return 1;
}
输出结果:
animal construct//构造函数释放顺序为:从父类到子类
fish construct
fish deconstruct//析构函数释放顺序为:从子类到父类
animal deconstruct