如何将一个对象的值复制到另一个对象中(25分)

  • 主题发起人 主题发起人 mycwcgr_temp
  • 开始时间 开始时间
M

mycwcgr_temp

Unregistered / Unconfirmed
GUEST, unregistred user!
如何将一个对象的值复制到另一个对象中
下面两个对象myaa,mybb都是从Tobject继承的,没有assign方法,如何方便的将myaa中的所有属性值
复制到mybb中去?mybb:=myaa 仅仅复制了指针.

unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type tbb=class(Tobject)
tindex:integer;
tstr:string
end;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
myaa:tbb;
mybb:tbb;
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
myaa:=tbb.Create;
mybb:=tbb.create;
myaa.tindex:=5;
myaa.tstr:='cw';
mybb:=myaa;
{仅仅复制了指针}
//mybb.assign(aa);{不能执行,因为它们不是从TPersistent继承的}
end;

end.
 
那为什么不从TPersistent继承呢?
 
up
myaa:=tbb.Create;
//mybb:=tbb.create;
myaa.tindex:=5;
myaa.tstr:='cw'
mybb:=myaa;
或者重载:=运算符 [^]
 
use pointer
 
自己加个assign
 
重载等号运算符
 
试试mybb^:=myaa^;
 
重载:=
 
加个assign来得方便些,也不难啊
 
怎样加???????????
给一个Example
 
看VCL的源代码吧
 
我看了一下,还是要重载,呵呵,相当于重载运算符,就是将每个属性赋给对方吧,没意义
 
BorLand为什么不作一个ObjAssign函数,
这样多好:
Function ObjAssign(SndDestObj:TObject;SndSreObj:TObject):Boolean;
 
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
tbb=class(TPersistent)
protected
procedure AssignTo(Dest: TPersistent);
Override;
Public
tindex:integer;
tstr:string;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
myaa:tbb;
mybb:tbb;
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
{$R *.dfm}
{ tbb }
procedure tbb.AssignTo(Dest: TPersistent);
begin
if Dest is tbb then
begin
with (Dest as tbb) do
begin
tindex:=Self.tindex;
tstr:=Self.tstr;
end;
end else
inherited;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
myaa:=tbb.Create;
mybb:=tbb.create;
myaa.tindex:=5;
myaa.tstr:='cw';
// mybb:=myaa;
{仅仅复制了指针}
mybb.assign(myaa);{不能执行,因为它们不是从TPersistent继承的}
end;

end.
 
接受答案了.
 
后退
顶部