72 lines
1.1 KiB
C++
72 lines
1.1 KiB
C++
// 动态类型转换
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
class A
|
|
{
|
|
protected:
|
|
int x;
|
|
|
|
public:
|
|
A(int x) : x(x) {}
|
|
void show()
|
|
{
|
|
cout << "A x = " << x << endl;
|
|
}
|
|
};
|
|
|
|
class B : public A
|
|
{
|
|
public:
|
|
B(int x) : A(x) {}
|
|
void print()
|
|
{
|
|
cout << "B print x = " << x << endl;
|
|
}
|
|
};
|
|
|
|
class C
|
|
{
|
|
};
|
|
|
|
void test1()
|
|
{
|
|
int a = 65;
|
|
// 动态转化不支持基本数据类型之间的转换
|
|
// char c = dynamic_cast<char>(a);
|
|
// char *c = dynamic_cast<char *>(&a);
|
|
// cout << "c = " << c << endl;
|
|
}
|
|
|
|
void test2()
|
|
{
|
|
A a1 = A(10);
|
|
B b1 = B(20);
|
|
|
|
// 上行转换
|
|
A &a2 = dynamic_cast<A &>(b1);
|
|
a2.show();
|
|
// a2.print(); // 不存在 print 成员函数
|
|
b1.print();
|
|
|
|
// 下行转换: 动态转换不支持(安全)
|
|
// B &b2 = dynamic_cast<B &>(a2);
|
|
// b2.print();
|
|
B &b3 = static_cast<B &>(a2);
|
|
b3.print();
|
|
}
|
|
|
|
// 不相关类型的转换: 不可动态转换
|
|
void test3()
|
|
{
|
|
A *a = new A(20);
|
|
// C *p = dynamic_cast<C *>(a);
|
|
}
|
|
|
|
int main()
|
|
{
|
|
test3();
|
|
return 0;
|
|
}
|