一、继承的数据权限变化之后的权限突破
继承之后,父类数据到子类之后的权限变化之后,对数据权限的突破,
主要有三种方法:
公开外部接口
友元函数
友元类
二、友元类
在哪个类中声明友元类,就获得对这个类的私有成员的访问权力.
看程序举例:
#include <iostream>
using namespace std;
class A{
int x;
int y;
public:
A():x(10),y(123){
}
friend class B;
friend class C;
};
class B :public A{
public:
void show(){
cout << x << ":" << y << endl;
}
};
class C{
public:
void show(){
A a;
cout << a.x << ":" << a.y << endl;
}
};
int main(){
B b;
b.show();
c.show();
}
三、继承中构造函数和析构函数的调用顺序
构造函数和析构函数是不能被继承的,但可以调用。
子类一定会调用父类的构造函数。
子类默认调用父类的无参构造,也可以指定调用构造函数。
析构函数的调用和构造的调用顺序相反。
程序举例:
#include <iostream>
using namespace std;
class A{
int x;
public:
A(){
cout << "A()" << endl;
}
A(int x){
cout << "A(int)" << endl;}
~A(){
cout << "~A()" << endl;
}
};
class B:public A{
public:
B():A(100){
cout << "B()" << endl;
}
~B(){
cout << "~B()" << endl;
}
};
int main(){
B b;
}
四、继承中的拷贝构造函数 和 赋值运算符函数
拷贝构造函数和赋值运算符也不能被继承
但子类不提供拷贝构造 和 赋值运算符时,子类默认调用父类的拷贝构
造函数。
但子类一旦提供拷贝构造函数 和 赋值运算符函数,则不再调用父类的
拷贝构造函数 和 赋值运算符。
假如我们子类提供了拷贝构造函数和赋值运算符函数:
拷贝构造函数在初始化参数列表中调用即可
赋值运算符函数需要使用类名::
程序举例:
#include <iostream>
using namespace std;
class A{
public:
A(){
}
A(const A& a){
cout << "A(const A&)" << endl;
}
A& operator=(const A& a){
cout << "operator=(const A&)" << endl;
}
};
class B:public A{
int *pi;
public:
B(){
}
B(const B& b):A(b){
cout << "B(B&)" << endl;
}
B& operator=(const B& b){
A::operator=(b);
cout << "operator=(B&)" << endl;
}
};
int main(){
B a;
B b=a;
}
五、名字隐藏机制(name hide)
4.1概念
子类中如果定义了和父类型同名的数据,则会把父类中的数
据隐藏掉。
名字隐藏时对函数的返回值和参数列表没有限制,但是函数
设计了参数,调用会有歧义,因此调用时应该传参。
需要调用父类的数据,需要在数据前加类型::
4.2举例
#include <iostream>
using namespace std;
class Animal{
public:
int x;
static int acount;
Animal(int x=100):x(x){
}
void show(){
cout << "this is Animal show()" << endl;
}
};
int Animal::acount=99;
class Dog:public Animal{
public:
int x;
static int acount;
void show(){
Animal::show();
cout << "this is