指向Perl6中的类的构造函数的指针 [英] pointer to constructor to a class in perl6

查看:72
本文介绍了指向Perl6中的类的构造函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Perl 6编写一些类,只是为了测试Perl 6的类和方法。

I am trying to write some classes with Perl 6 just for testing out Perl 6 classes and methods.

这里是代码:

class human1 {
    method fn1() {
        print "#from human1.fn1\n";
    }
}

class human2 {
    method fn1() {
          print "#from human2.fn1\n";
    }
}

my $a = human1.new();
my $b = human2.new();

$a.fn1();
$b.fn1();

print "now trying more complex stuff\n";

my $hum1_const = &human1.new;
my $hum2_const = &human2.new;

my $c = $hum2_const();
$c.fn1();

基本上我希望能够使用 human1 构造函数或 human2 构造函数,以便能够动态构建 $ c 对象。但是我收到以下错误:

Essentially I want to be able to use either the human1 constructor or human2 constructor to be able to build $c object dynamically. But I'm getting the following error:

Error while compiling /usr/bhaskars/code/perl/./a.pl6
Illegally post-declared types:
    human1 used at line 23
    human2 used at line 24

如何使用函数指针创建 $ c 以选择我使用的构造函数?

How do I create $c using the function pointers to choose which constructor I use?

推荐答案

我认为这是LTA错误的情况。我了解您想要实现的是一个lambda,它将为您创建一个新的 human1 human2 对象。您这样做的方法是不正确的,它引起的错误令人困惑。

I think this is a case of an LTA error. What I understand you want to achieve, is a lambda that will create a new human1 or human2 object for you. The way you do that is not correct, and the error it causes is confusing.

my $hum1_const = -> { human1.new };
my $hum2_const = -> { human2.new };

将是正确的方法。虽然,我认为这有点令人困惑。由于 human1 human2 已经是常量,因此可以将其分配给变量,然后只需调用 new

would be a correct way of doing this. Although, I would consider this a bit of an obfuscation. Since human1 and human2 are already constants, you can assign them to a variable, and then just call new on that:

my $the_human = $condition ?? human1 !! human2;
my $c = $the_human.new;
$c.fn1;

这有意义吗?

这篇关于指向Perl6中的类的构造函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆