Object-oriented Perl 2

xiaoxiao2021-03-06  37

Object-oriented Perl 2

Constructor

Let's first look at the most important function Bless in the constructor.

I checked the meaning of Bless, I feel that the seventh interpretation in the traditional American dictionary is in line with the situation:

Bless: to endow, as with talent. (give, if you can)

In Perl, Bless converts the reference to an object, which gives both the talents of the reference object.

In the previous section, Bless accepts two parameters. When the first parameter is referenced, the second is the package to reference Bless.

If the second parameter is ignored, use the current package.

The simplest constructor can make the following form:

Package Hero;

Sub new {

Bless ()

}

This is equivalent to the following constructor:

Package Hero;

Sub new {

MY $ SELF = {};

Bless $ Self, "Hero";

RETURN $ SELF;

}

Such a constructor is no problem with the case where there is only one class. But when inheriting, this simple constructor is

Unable to achieve the features you want.

For example: a superman's class inherits and HERO class, but he does not have its own constructor, when you create a superman,

The Hero constructor is automatically called. Superman-> New ("superman"); actually get a HERO,

Because of this Bless $ Self, "Hero"; there is no payment of Superman-> New ("superman");

The following constructor can solve this problem:

Package Hero;

Sub new {

MY $ Class = Shift;

MY $ SELF = {};

Bless $ SELF, $ Class;

RETURN $ SELF;

}

How to construct a similar object from an object

Slightly transform the previous constructor we can construct a similar object with a reference to an object.

Package Hero;

Sub new {

MY $ invocant = shift;

MY $ Class = Ref ($ invocant) || $ invocant;

MY $ SELF = {};

Bless $ SELF, $ Class;

RETURN $ SELF;

}

-----------------------------------------

Ref

REF EXPR

Ref

If the expr is a reference, the REF operator returns a true value, otherwise it returns false. The returned value depends on this reference

The type of thing referenced. Built-in types include: Scalar, Array, Hash, Code, Glob, REF, LVALUE, IO :: Handle.

If this reference object has bless a package, then returns the name of the package.

转载请注明原文地址:https://www.9cbs.com/read-66497.html

New Post(0)