继承TPersistent类

来源:互联网 发布:工控软件下载 编辑:程序博客网 时间:2024/05/01 09:16

在类的实例之间,传递值,可以用=,对于简单数据以值传递,对于复杂数据,如结构,是以指针传递。要实现深度拷贝可以实现拷贝函数或者继承TPersistent类。TPersistent类的方法:    Assign()    这个公用方法允许一个组件把与另一个组件相关的数据赋给自己。    AssignTo()  这是个私有方法,TPersistent派生类必须实现它的定义。当这个方法被调用时,TPersistent将自己抛出一个异常。一个组件可以通过AssignTo()把自己的数据值赋给另一个实例或类,与Assign()相反。DefineProperties() 这个私有方法允许组件编写者定义组件如何存储特别的或非公用的属性。该方法一般为组件存储诸如二进制数据等非简单数据类型的数据。#ifndef __assign__#define __assign__class theData:TPersistent{   private:   public:     int a;     int b;     void Assign(theData *Source)//覆盖父类中的Assign函数     {        a = Source->a;        b = Source->b;     }};#endif调用方法如下:#include <vcl.h>#pragma hdrstop#include "Unit1.h"#include "Assign.h"//---------------------------------------------------------------------------#pragma package(smart_init)#pragma resource "*.dfm"TForm1 *Form1;//---------------------------------------------------------------------------__fastcall TForm1::TForm1(TComponent* Owner)        : TForm(Owner){}//---------------------------------------------------------------------------void __fastcall TForm1::Button1Click(TObject *Sender){    theData *a = new theData;    theData *b = new theData;    a->a = 20;    a->b = 90;    b->Assign(a);    ShowMessage(b->a);    ShowMessage(b->b);}//---------------------------------------------------------------------------
AssignTo()可以被子类覆盖,用来复制自身的数据到另一个对象实例。在C++中私有方法不能被子类覆盖,虚函数除外。



0 0