C++向上转型

将派生类对象的成员数据赋值给基类对象(仅限成员数据)

#include 
using namespace std;

class Base
{
protected:
    int a;

public:
    Base(int a)
    {
        this->a = a;
    }
    ~Base()
    {
    }

    void print()
    {
        cout << "Base..." << "a = " << a << endl;
    }
};

class Derived:public Base
{
protected:
    int b;

public:
    Derived(int i, int j):Base(i)
    {
        b = j;
    }
    ~Derived()
    {
    }

    void print()
    {
        cout << "Derived..." << "b = " << b << endl;
    }
};

int main()
{
    Base b(1);
    Derived d(2, 3);

    b = d;
    b.print();
    d.print();

    return 0;
}

你可能感兴趣的:(C++向上转型)