简体   繁体   English

如何创建自定义组件? 访问私有字段时出错

[英]How to create a custom components? Error accessing private field

I want to create a new component derived from TPanel. 我想创建一个从TPanel派生的新组件。 This new component has only one private field: "obj" (a TObject). 这个新组件只有一个私有字段:“ obj”(一个TObject)。
In the constructor I create the object. 在构造函数中,我创建对象。 Later, when I try to access the object it is NULL. 以后,当我尝试访问该对象时,它为NULL。 Why? 为什么?

Header: 标头:

class PACKAGE TMyClass : public TPanel
{
private:
    TObject *obj;
protected:
public:
   __fastcall TMyClass(TComponent* Owner);
   void Stuff();
};

CPP file: CPP文件:

__fastcall TMyClass::TMyClass(TComponent* Owner)
   : TPanel(Owner)
{
    Caption        = "";
    DoubleBuffered = True;
    Width          = 385;
    Height         = 65;

    TObject *obj= new TObject;     //obj gets an address here
}



void TMyClass::Stuff()      // <---- I call this method in the OnClick event of a button.
{
   Caption = obj->ClassName();    //obj is NULL here
}
//---------------------------------------------------------------------------








namespace Uvolctrl
{ void __fastcall PACKAGE Register()
   {  TComponentClass classes[1] = {__classid(TMyClass)};
       RegisterComponents(L"Samples", classes, 0); } }



static inline void ValidCtrCheck(TMyClass *)   // assure that the components do not have any pure virtual functions.
{ new TMyClass(NULL);    }

在构造函数中,您正在创建一个类实例,并将其分配给名为obj的局部变量,而不是您的私有obj成员变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM