作为继承,主要有三种:公有继承,私有继承(默认继承方式),保护继承。
公有继承:
基类中的公有成员在派生类中仍公有;
基类中的保护成员在派生类中仍保护;
基类中的私有成员在派生类中不可见,仅基类可见。
私有继承:
基类中的公有成员在派生类中为私有;
基类中的保护成员在派生类中为私有;
基类中的私有成员在派生类中不可见,仅基类可见。
保护继承:
基类中的公有成员在派生类中为保护;
基类中的保护成员在派生类中为保护;
基类中的私有成员在派生类中不可见,仅基类可见。
通过继承机制,派生类继承了基类的成员,所继承的成员只属于派生类,即基类和派生类各有一份这样的成员,这点很重要。
接下来,我们不慌看继承,回到类来看:(个人理解所谓可见性即是调用权限!)
#include《iostream》
using namespace std;
class A{
public:
void dump()const{…}
protected:
void set(){……}
private:
void get(){……}
};
int main()
{
A a;
a.dump();//ok!
/* a.set(); */ //wrong!
/* a.get(); */ //wrong!
return 0;
}
函数set()和get()在main函数中都不能调用,说明它们的调用权限仅属于类,即对main不可见。同理可知dump()。
下面我们以公有继承为例:
#include《iostream》
using namespace std;
class A{
public:
void dump()const{…}
protected:
void get_x(){x++;}
private:
int x;
};
class B:public A
{
public:
void get(){ get_x();}
/* void get_y(){ y=x;} */
void compare(A &a){ a.get_x();}
protected:
void set(){…}
private:
int y;
};
int main()
{
B b;
A a;
/* b.get_y(); */ //wrong! x在B类不可见,不能访问。
b.get();//ok! 由于x是私有的,所以派生类不可见,但能间接访问。
/* b.compare(a); */ //wrong!这个是我之前一直没想通的,但是现在清楚了。因为对象a调用的get_x()权限仅属于A,所以对B不可见。
return 0;
}
于是我们知道,在派生类不可见的成员并不是不可访问的,可以通过间接的方式访问!
总结上面的,做了一张表:(注:派生类中成员的可见性是指继承来的和自身添加的成员。)
公有继承:
基类中的公有成员在派生类中仍公有;
基类中的保护成员在派生类中仍保护;
基类中的私有成员在派生类中不可见,仅基类可见。
私有继承:
基类中的公有成员在派生类中为私有;
基类中的保护成员在派生类中为私有;
基类中的私有成员在派生类中不可见,仅基类可见。
保护继承:
基类中的保护成员在派生类中为保护;
基类中的私有成员在派生类中不可见,仅基类可见。
通过继承机制,派生类继承了基类的成员,所继承的成员只属于派生类,即基类和派生类各有一份这样的成员,这点很重要。
接下来,我们不慌看继承,回到类来看:(个人理解所谓可见性即是调用权限!)
#include《iostream》
using namespace std;
class A{
public:
void dump()const{…}
protected:
private:
void get(){……}
};
int main()
{
A a;
a.dump();//ok!
/* a.set(); */ //wrong!
/* a.get(); */ //wrong!
}
函数set()和get()在main函数中都不能调用,说明它们的调用权限仅属于类,即对main不可见。同理可知dump()。
下面我们以公有继承为例:
#include《iostream》
using namespace std;
class A{
public:
void dump()const{…}
protected:
private:
int x;
};
{
public:
void get(){ get_x();}
/* void get_y(){ y=x;} */
void compare(A &a){ a.get_x();}
protected:
void set(){…}
private:
int y;
};
{
B b;
A a;
/* b.get_y(); */ //wrong! x在B类不可见,不能访问。
b.get();//ok! 由于x是私有的,所以派生类不可见,但能间接访问。
/* b.compare(a); */ //wrong!这个是我之前一直没想通的,但是现在清楚了。因为对象a调用的get_x()权限仅属于A,所以对B不可见。
return 0;
}
于是我们知道,在派生类不可见的成员并不是不可访问的,可以通过间接的方式访问!
总结上面的,做了一张表:(注:派生类中成员的可见性是指继承来的和自身添加的成员。)
