WEB开发网
开发学院软件开发C++ C++的虚函数与对象切割 阅读

C++的虚函数与对象切割

 2010-12-12 07:21:10 来源:WEB开发网   
核心提示:一道非常基础的题目,请回复下面程序的结果:#include <iostream.h>class ClassA{public: void fun1(); void fun2(); virtual void fun3();};void ClassA::fun1(){ cout <&

一道非常基础的题目,请回复下面程序的结果:

#include <iostream.h>

class ClassA
{
public:
    void fun1();
    void fun2();
    virtual void fun3();
};

void ClassA::fun1()
{
    cout << "ClassA.fun1"<<endl;
};

void ClassA::fun2()
{
    cout << "ClassA.fun2"<<endl;
};

void ClassA::fun3()
{
    cout << "ClassA.fun3"<<endl;
};


class ClassB : public ClassA
{
public:
    void fun1();
    void fun2();
    virtual void fun3();
};

void ClassB::fun3()
{
    cout << "ClassB.fun3"<<endl;
};

class ClassC : public ClassB
{
public:
    void fun1();
    void fun2();
    virtual void fun3();
};

void ClassC::fun3()
{
    cout << "ClassC.fun3"<<endl;
};

void main()
{
    ClassA *a[3];
    ClassA a1;
    ClassB b1;
    ClassC c1;


    a1.fun3();
    b1.fun3();
    c1.fun3();

    a[0] = &a1;
    a[1] = &b1;
    a[2] = &c1;
    cout << "virtual function array test" <<endl;
    for(int i=0;i<3;i++)
    {
        a[i]->fun3();
    }

    cout << "((ClassA)&b1).fun3():";
    ((ClassA*)&b1)->fun3();
    //object slicing
    cout << "object slicing"<<endl;
    cout <<"((ClassA)b1).fun3():"; 
    ((ClassA)b1).fun3();
}

Tags:函数 对象 切割

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接