gpt4 book ai didi

Perl Moose 父类与子类一起转换

转载 作者:行者123 更新时间:2023-12-04 23:31:29 28 4
gpt4 key购买 nike

package Point;
use Moose;

has 'x' => (isa => 'Int', is => 'rw');
has 'y' => (isa => 'Int', is => 'rw');

package Point3D;
use Moose;

extends 'Point';

has 'z' => (isa => 'Int', is => 'rw');

package main;

use Data::Dumper;

my $point1 = Point->new(x => 5, y => 7);
my $point3d = Point3D->new(z => -5);

$point3d = $point1;
print Dumper($point3d);

是否可以将父类转换为 C++ 等子类?在我的例子中, $point3d 现在是一个 Point 而不是 Point3D 包括 Point。

最佳答案

看看Class::MOP documentation on CPAN ,尤其是 clone_objectrebless_instance方法:

sub to_3d {
my ($self, %args) = @_;
return Point3D->meta->rebless_instance(
$self->meta->clone_object($self),
%args,
);
}

然后像下面这样使用它:
my $point_3d = $point->to_3d(z => 7);

这也会照顾到处理新指定的 %args就好像它们是由构造函数传入的一样。例如。在这个构建过程中,构建器、默认值和类型约束都被考虑在内。

关于Perl Moose 父类与子类一起转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4583719/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com