代码之家  ›  专栏  ›  技术社区  ›  IceCold

如何在C++ Builder中实现Delphi保护的成员访问技巧?

  •  2
  • IceCold  · 技术社区  · 7 年前

    我需要进入TControlItem.InternalSetLocation这是受保护的。我相信你会做的

    type
      THackControlItem = class(TControlItem);
    

    如何在C++ Builder中实现这一点?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Spektre    7 年前

    我想这是个不错的把戏 Remy Lebeau

    //---------------------------------------------------------------------------
    #ifndef _TDirectMemoryStream
    #define _TDirectMemoryStream
    class TDirectMemoryStream:TMemoryStream // just for accessing protected SetPointer
        {
    public:
        void SetMemory(BYTE *ptr,DWORD siz) { SetPointer(ptr,siz); Position=0; };
        };
    #endif
    //---------------------------------------------------------------------------
    

    您只需创建一个新类,它是您要访问的类的后代。现在只需为受保护成员添加get/set函数。。。

    现在使用:

    TMemoryStream *mem=new TMemoryStream(); // original class instance you want to access
    
    // overtype to our new class and access/use you get/set ...
    ((TDirectMemoryStream*)(mem))->SetMemory(hdr->lpData,hdr->dwBytesUsed);
    
    delete mem; // release if not needed anymore
    

    我用它来提供一个自定义内存数据流 hdr TJPEGImage 类,而不是将数据写入文件并在每帧加载回它。。。

    这里还有一个例子:

    class A
        {
    protected:
        int x;
    public:
        int getx(){ return x; }
        };
    
    class hack_A:A
        {
    public:
        void setx(int _x){ x=_x; }
        };
    
    void test()
        {
        A a;
        hack_A *ha=(hack_A*)&a;
        ha->setx(10);
        a.getx(); // print the x somwhere
        }
    

    然而,这对私人成员不起作用。。。在这种情况下,它也是可行的,但需要访问 A

    class A
        {
    protected:
        int x;
    private:
        int y;
    public:
        int getx(){ return x; }
        int gety(){ return y; }
        friend class hack_A;        // but this one requires access to A soourcecode
        };
    
    class hack_A:A
        {
    public:
        void setx(int _x){ x=_x; }
        void sety(int _y){ y=_y; }
        };
    
    void test()
        {
        A a;
        hack_A *ha=(hack_A*)&a;
        ha->setx(10);
        ha->sety(20);
        a.getx(); // print the x somwhere
        a.gety(); // print the x somwhere
        }
    
        2
  •  0
  •   serge    7 年前

    在Delphi中,您需要继承类,但也要重写并公开受保护的函数。但是,我不建议在生产代码中使用它。

    class THackControlItem : public TControlItem
    {
    public:
        void __fastcall InternalSetLocation(int AColumn, int ARow, bool APushed, bool MoveExisting)
        {
            TControlItem::InternalSetLocation(AColumn, ARow, APushed, MoveExisting);
        }
    };
    

    在程序中

    TControlItem* ci = ...;
    static_cast<THackControlItem*>(ci)->InternalSetLocation(...);