类型兼容规则的使用(P204/205)

/*

*类型兼容性规则:
是指在需要基类对象的任何地方,都可以使用公有派生类的对象来替代,也称为赋值兼容规则。--》通过公有继承,派生类得到了基类中除构造函数、析构函数之外的私有成员。

在公有派生的情况下,有以下3条类型兼容规则。
a.派生类的对象可以赋值给基类对象。 eg:b1 = d1;
b.派生类对象可以用来初始化基类引用。eg:B &rb = d1;
c.派生类对象的地址可以赋值给基类指针,即派生类的指针可以赋值给基类的指针。eg:pb1 = &d1;

*/

#include<iostream>
#include<string>
using namespace std;

class A
{
int an;
public:
A(){}
A(int n)
{
an=n;
}
void print()
{
cout<<"A的对象:";
cout<<"an:"<<an<<endl;
}
void print(int k) //不同的输出格式
{
cout<<"an:"<<an<<endl;
}
};

class B:public A //公有派生
{
int bn;
public:
B(int n):A(2*n)
{
bn=n;
}
void print()
{
cout<<"B的对象:";
A::print(1);
cout<<",bn:"<<bn<<endl;
}
};

int main()
{
A a(10);
B b(20);
a.print();
b.print();
a=b; //派生类对象赋值给基类对象
a.print();
b.print();
return 0;
}

posted @ 2020-03-23 12:13  CollisionDimension  阅读(340)  评论(0)    收藏  举报