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(向上造型)