1. 子类 -> 父类
父类 -> Base
#include<isotream>
using namespace std;
class Base{
public:
Base() : pub_att(1){}
int pub_att;
};
public继承的子类1 -> Derived1
class Derived1 : public Base{
public:
Derived1() : att(2){}
int att;
};
private继承的子类2 -> Derived2
class Derived2 : private Base{
public:
Derived2() : att(3){}
int att;
};
需要类型转换的函数 -> class_con
void class_con(Base & A_Base){
cout << "class_con is called!" << endl;
cout << "Base::pub_att = " << A_Base.pub_att << endl;
}
声明对象
int main(){
Derived1 A_Derived1;
Derived2 A_Derived2;
Base A_Base1, A_Base2;
对象转型
public继承的子类对象自动向上转型
:
A_Base1 = A_Derived1;
private继承的子类对象不可转型
:
指针和引用转型
public继承的对象指针和引用自动向上转型
:
Base * base_ptr1 = &A_Derived1;
class_con(A_Derived1);
private继承的对象指针和引用普通强制转型
:
Base * base_ptr2 = (Base *)&A_Derived2;
class_con((Base &)A_Derived2);
}
输出:
class_con is called!
Base::pub_att = 1
class_con is called!
Base::pub_att = 1
- 父类型指针和引用还是会访问父类型的成员!
- private继承的对象指针和引用,父类的成员子类全部继承为private,普通强制转型后,将恢复为原来的public,所以使用class_on函数可以访问父类(见1)的pub_att。
2. 父类 -> 子类
#include<iostream>
using namespace std;
父类
class Base{
private:
int pri_att;
public:
Base() : pri_att(1){}
};
子类
class Derived : public Base{
public:
int Derived_att;
Derived() : Derived_att(2) {}
};
传指针,传引用,传值
void class_cast_ptr(Derived * A_Derived){
cout << "A_Derived->Derived_att = "
<< A_Derived->Derived_att << endl;
}
void class_cast_ref(Derived & A_Derived){
cout << "A_Derived.Derived_att = "
<< A_Derived.Derived_att << endl;
}
void class_cast_val(Derived A_Derived){
cout << "A_Derived.Derived_att = "
<< A_Derived.Derived_att << endl;
};
int main(){
Base A_Base;
对象转型
任何对象不可向下转型
指针和引用转型
父类对象指针static_cast强制向下转型
:
Base * base_ptr = new Derived;
class_cast_ptr(static_cast<Derived *>(base_ptr));
父类对象引用static_cast强制向下转型
:
class_cast_ref(static_cast<Derived &>(A_Base));
}
输出:
A_Derived->Derived_att = 2
A_Derived.Derived_att = 2096008816
- 子类对象指针先向上转型,又向下转型,所以子类对象有值(子类指针访问子类成员),A_Derived->Derived_att = 2!!
- 父类对象指针直接向下转型,所以子类对象无值,不可知,A_Derived.Derived_att = 2096008816