8000 动态声明子类 · Issue #20 · holdyounger/ScopeBlog · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
动态声明子类 #20
Open
Open
@holdyounger

Description

@holdyounger

动态声明子类

#include <iostream>
#include <cstdlib>
using namespace std;
class BaseClass 
{
public:
    BaseClass()
    {
        cout<<"BaseClass Construct"<<endl;
    }
    virtual ~BaseClass()
    {
        cout<<"BaseClass Destruct"<<endl;
    }
    virtual void  TestFunction()
    {
        cout<<"BaseClass TestFunction"<<endl;
    }
protected:
    int Test;
};
 
class SonClass : public BaseClass
{
public:
    SonClass()
    {
        cout<<"SonClass Construct"<<endl;
    }
    virtual ~SonClass()
    {
        cout<<"SonClass Destruct"<<endl;
    }
    virtual void  TestFunction()
    {
        cout<<"SonClass TestFunction"<<endl;
    }
};
 
typedef void           *LPVOID;
template<class _baseClass, class _derivedClass>
bool DoDynamicSubclassing(_baseClass *pBaseObj)
{
    if(pBaseObj)
    {
        static_assert(sizeof(_baseClass) == sizeof(_derivedClass), "DynamicSubclassing to _derivedClass must not have its own members");
        _derivedClass _derivedClassinstance;
        LPVOID *pBaseVirtPtr = (LPVOID*)pBaseObj, *pDerivedVirtPtr = (LPVOID*)&_derivedClassinstance;
        //assign the virtual ptr of the derived class
        *pBaseVirtPtr = *pDerivedVirtPtr;
        return true;
    }
    return false;
}
 
int main()
{
    BaseClass *Test = new BaseClass;
    cout << *(int*)Test << endl;
    DoDynamicSubclassing<BaseClass, SonClass>(Test);
    Test->TestFunction();
    cout << *(int*)Test << endl;
    
    cout << " ————————- " <<endl;
    BaseClass aaaa;
    cout << *(int*)&aaaa << endl;
    DoDynamicSubclassing<BaseClass, SonClass>(&aaaa);
    aaaa.TestFunction();
    cout << *(int*)&aaaa << endl;
    return 0;
}

blog link 动态声明子类

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0