父子间的赋值兼容

子类对象可以当做父类对象使用(兼容性)

子类对象可以直接赋值给父类对象

子类对象可以直接初始化父类对象

父类指针可以直接指向子类对象

父类引用可以直接引用子类对象

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.

问题分析:

编译期间,编译器只能根据指针的类型判断所指向的对象

根据赋值兼容,编译器认为父类指针指向的是父类对象

因此,编译结果只可能是调用父类中定义的同名函数

Slide9.PNG

小结:

子类对象可以当做父类对象使用

父类指针可以正确的指向子类对象

父类引用可以正确的代表子类对象

子类中可以重写父类中的成员函数


YingLi
6 声望4 粉丝

From zero to hero.