22. 向上造型

B 父类
D 子类

一个D的对象,可以交给B的变量.
一个D的指针,可以交给B的指针.
一个D的reference, 可以交给B的reference.

如果B是A的子类,那么B的对象可以被当做A的对象来看待/使用.

#include <iostream>
using namespace std;

class A
{
 public:
   int i;
 public:
   A():i(10) {}  
};

class B:public A
{    
};

int main()
{
   A a;
   B b;
   cout << a.i << " " << b.i << endl; // 10 10
   cout << sizeof(a) << " " << sizeof(b) << endl; //4 4 
   int *p = (int*)&a;
   cout << p << " " << *p << endl; //0x7fff57659bf0 10
   p = (int*)&b;
   cout << p << " " << *p << endl; //0x7fff57659be8 10
   return 0;
}

int main()
{
   A a;
   B b;
   cout << a.i << " " << b.i << endl; // 10 10
   cout << sizeof(a) << " " << sizeof(b) << endl; //4 4 
   int *p = (int*)&a;
   cout << p << " " << *p << endl; //0x7fff57659bf0 10
   *p = 20;
   cout << a.i << endl; // 20
   p = (int*)&b;
   cout << p << " " << *p << endl; //0x7fff57659be8 10
   return 0;
}
#include <iostream>
using namespace std;

class A
{
 public:
   int i;
 public:
   A():i(10) {}  
};

class B:public A
{    
  private:
    int j;
  public:
    B():j(30) {}
    void f() { cout << " B.j = " << j << endl; }

};

int main()
{
   A a;
   B b;
   cout << a.i << " " << b.i << endl; // 10 10
   cout << sizeof(a) << " " << sizeof(b) << endl; //4 8 
   int *p = (int*)&a;
   cout << p << " " << *p << endl; //0x7fff57659bf0 10
   *p = 20;
   cout << a.i << endl; // 20
   p = (int*)&b;
   cout << p << " " << *p << endl; //0x7fff57659be8 10
   p++;
   *p = 50;
   b.f(); //B.j = 50
   return 0;
}

子类的对象,当做父类的对象来看待,叫做upcasting(向上造型).

Manager是特殊的Employee.
Employee : 父类
Manager : 子类

Manager pete(“Pete”, “444-55-6666”, “Bakery”);
Employee* ep = &pete; // upcasting(向上造型)
Employee& er = pete; //upcasting(向上造型)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值