C++中三大继承方式的运行效果

#include <iostream>
using namespace std;
class A
{
public:
void inial(){};
int size;
protected:
int val;
private:
int price;
};
class B : public A
{
public:
int ret(const B b1, A a1)
{
int temp = this->val;
temp = val;
temp = b1.val;
temp = size;
//a1.size;//ok
a1.inial();//ok
//temp = a1.val;//error
//temp = price;//error
}
};
class C : protected A
{
public:
void  ret(const C c1,  A a1)
{
int temp = this->val;
temp = val;
temp = c1.val;
temp = size;
inial();
a1.inial();
a1.size;
//temp = a1.val;//error
//temp = price;//error
}
};
class D : private A
{
public:
void ret(const D d, A a)
{
int temp = size;//ok
temp = d.val;//ok
temp = val;//ok
inial();//ok
a.inial();//ok
a.size;//ok
//temp = price;//error
//temp = a.val;//error
//temp = price;//error
}
//int tmp = val;//error
};
int main()
{
B b;
b.inial();
b.size;
//b.price;//error
//b.val;//**********error
C c;
//c.size;//error
//c.inial();//error
D d;
//d.inial();//error
//d.size;//error
//d.val;//error
return 0;
}




总结:
对于基类中的private成员,无论采用什么方式继承,这些成员只能被基类的成员和友元访问;


下面的讨论只针对基类中的protected和public成员:


1.采用public方式继承,则基类中的public成员在派生类中成为public成员,派生类对象和派生类
里面当然可以直接访问它们;基类中的protected成员在派生类中成为protected成员,但是基类的
protected成员在派生类里面中只能通过派生类对象访问,不能通过基类的对象访问。当然在派生类外
不能通过派生类对象访问。


2.采用protected方式继承,则基类的public和protected成员都成为protected成员,此时基类中的
public成员在派生类类外不能通过派生类对象访问,在派生类类里按照派生类的protected成员特性访问;
基类的protected成员在派生类里面还是只能通过派生类对象访问,不能通过基类的对象访问。当然在
派生类外不能通过派生类对象访问。




3.采用private方式继承,则基类中的public和protected成员都成为private成员,此时基类中的
public成员被按照派生类的private成员特性进行访问;基类的protected成员在派生类里面还是
只能通过派生类对象访问,不能通过基类的对象访问。当然在派生类外不能通过派生类对象访问。























猜你喜欢

转载自blog.csdn.net/e1256325535/article/details/38760631
今日推荐