父子间的赋值兼容
子类对象可以当做父类对象使用(兼容性)
子类对象可以直接赋值给父类对象
子类对象可以直接初始化父类对象
父类指针可以直接指向子类对象
父类引用可以直接引用子类对象
48-1.cpp
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
int add(int i)
{
mi += i;
}
int add (int a,int b)
{
mi +=(a + b);
}
};
class Child : public Parent
{
public:
int mv;
int add(int x,int y,int z)
{
mv += (x + y + z);
}
};
int main()
{
Parent p;
Child c;
p = c;
Parent p1(c);
Parent& rp = c;
Parent* pp = &c;
rp.mi = 100;
rp.add(5);
rp.add(10,10);
pp->mv = 1000;
pp -> add(1,10,100);
return 0;
}
输出:
error
父子间的赋值兼容
当使用父类指针(引用)指向子类对象时
子类对象退化为父类对象
只能访问父类中定义的成员
可以直接访问被子类覆盖的同名成员
特殊的同名函数
子类中可以重定义父类中已经存在的成员函数
这种重定义发生在继承中,叫做函数重写
函数重写是同名覆盖的一种特殊情况
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
int add(int i)
{
mi += i;
}
int add (int a,int b)
{
mi +=(a + b);
}
void print()
{
cout<< "I'm Parent."<<endl;
}
};
class Child : public Parent
{
public:
int mv;
int add(int x,int y,int z)
{
mv += (x + y + z);
}
void print()
{
cout<< "I'm child."<<endl;
}
};
void how_to_print(Parent *p)
{
p->print();
}
int main()
{
Parent p;
Child c;
p.print();
c.print();
how_to_print(&p);
how_to_print(&c);
return 0;
}
输出:
I'm Parent.
I'm child.
I'm Parent.
I'm Parent.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。