Domanda

I am trying to define a class that will have a public ADOConnection which another app can set.

However, I cannot get the constructor working to create the ADOConnection variable. This is the code I have so far:

unit SuperheroClass;

interface

uses
  ADODB;

type
  TSuperhero = Class

  private
    MyQry: TADOQuery;
    constructor Create;
  public
    MyCon: TADOConnection;

end;

implementation

constructor TSuperhero.Create;
begin
  MyCon := TADOConnection.Create(self);
end;

end.

If I am not mistaken, I need to create these internal class variables using Self so that they will belong to the class, and then I can free them in the class destructor.

This code gives me an error:

[Error] SuperheroClass.pas(23): Incompatible types: 'TComponent' and 'TSuperhero'

What am I doing wrong here?

È stato utile?

Soluzione

You could declare TSuperhero = Class(TComponent).

A TComponent ancestor has the ability to own and manage other components

Also make sure that your Constructor is public if you want it visible to other units. i.e.:

public 
  constructor Create(AOwner: TComponent); override;

...

constructor TSuperhero.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  // TSuperhero.Self now owns MyCon and responsible for freeing it
  MyCon := TADOConnection.Create(Self); 
end;

If Superhero is needed across the application, I would instantiate TSuperhero like:

Superhero := TSuperhero.Create(Application);

And let the Application be the owner of Superhero also responsible for freeing it.


Just to add to my answer, Your class TSuperhero usage is very much like a TDataModule (TComponent), so maybe you should really use a centralized TDataModule - drop a TADOConnection on it, and so on, and use that instance across your application.

Altri suggerimenti

You can pass nil as the parameter to TADOConnection.Create. This does not prevent you from destroying it in the TSuperHero class destructor.

constructor TSuperhero.Create;
begin
  MyCon := TADOConnection.Create(nil);
end;

The parameter passed to the TADOConnection constructor is used when the control is dropped onto a form as a visual component. You are getting the compile error in your code because TSuperHero does not descent from TComponent.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top