c++多态多实例

#include <bits/stdc++.h>
using namespace std;
class A
{
public:
    A()
    {
        cout << "构造A" << endl;
        s = new char[20];
        memset(s, 0, 20);
        strcpy(s, "hahaha");
    }
    virtual ~A()
    {
        cout << "析构A" << endl;
        delete []s;
    }
    virtual void print()
    {
        cout << s << endl;
    }
private:
    char *s;
};
class B :  public A
{
public:
    B()
    {
        cout << "构造B" << endl;
        s = new char[20];
        memset(s, 0, 20);
        strcpy(s, "BBBBB");
    }
    virtual ~B()
    {
        cout << "析构B" << endl;
        delete []s;
    }
    virtual void print()
    {
        cout << s << endl;
    }
private:
    char *s;
};

void ok(A *obj)
{
    obj->print();
}
void okk(A obj)
{
    obj.print();

}

1.

int main()
{
    B *b = new B;
    A *obj = b;
    obj->print();
    delete b;
    
    /*构造A
    构造B
    BBBBB
    析构B
    析构A*/
}

2.

int main()
{
    B *b = new B;
    A *obj = b;
    obj->print();
    delete obj;

    /*构造A
    构造B
    BBBBB
    析构A*/
}

3.

int main()
{
    B b;
    A a = b;
    A *pa = &b;
    a.print();//这里的a就是一个A类型的变量,它的内存布局在赋值的时候已经从B转换到A了,多于的数据都被丢弃,因此其就是一个A类型的变量。
    pa->print();//其是一个指针,其类型虽然是A,但指向的区域的内容却是一个B类型的内存结构,虽然内存结果的布局与A兼容,但其虚函数表中的Test却是B的实现

    /*构造A
    构造B
    hahaha
    BBBBB
    析构A
    析构B
    析构A*/
}

4.

int main()
{
    B *b = new B;
    ok(b);

    /*构造A
    构造B
    BBBBB*/
}

5.

int main()
{
    B *b = new B;
    ok(b);
    delete b;
    
    /*构造A
    构造B
    BBBBB
    析构B
    析构A*/
}

6.

int main()
{
    B b;
    okk(b);

    /*构造A
    构造B
    hahaha
    析构A
    析构B
    析构A*/
}

7.

int main()
{
    B *b = new B;
    A a;
    b = &a; //报错,不能让子类指针指向父对象
    ok(b);
}
posted @ 2019-04-27 11:18  LesRoad  阅读(1121)  评论(0编辑  收藏  举报