qfedu-cpp-level/day7/d15.cpp

43 lines
866 B
C++

// 静态类型转换
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class A
{
public:
int x;
A(int x) : x(x) {}
};
class B : public A
{
public:
int y;
B(int x, int y) : A(x), y(y) {}
};
int main()
{
A *a = new A(5);
B *b = new B(10, 20);
A *c = static_cast<A *>(b); // 静态上行转换,子类指针向父类指针转换
// cout << "a.x = " << a->x << endl;
// cout << "b.x = " << b->x << ", b.y = " << b->y << endl;
// cout << "b = " << b << endl;
// cout << "c = " << c << endl;
// cout << "c.x = " << c->x << endl;
// B *b2 = static_cast<B *>(a); // 下行转换,父类指针向子类指针转换
// B *b2 = (B *)a; // 强制下行转换,不安全
// cout << "b2.x = " << b2->x << ", b2.y = " << b2->y << endl;
delete a;
delete b;
return 0;
}