我有一个调用函数的Perl程序,在这种情况下ref,检查结果.具体来说,我正在测试一个变量是一个哈希引用.在那种情况下,ref将返回'HASH'.我测试了它,它工作.
然后我决定记录它,添加一个print显示相同调用的结果,但它无法正常工作.这是一个简化版本:
use strict;
use warnings;
my $book_ref = {};
$book_ref->{'title'} = 'The Lord of the Rings';
if (ref $book_ref eq 'HASH') {
print "ref \$book_ref is a " . ref $book_ref . "\n";
}
print "Program is over\n";
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,这是输出:
ref $book_ref is a Program is over
Run Code Online (Sandbox Code Playgroud)
尽管使用strict并且warnings既没有错误也没有警告.
调用ref是完全相同的(它是复制和粘贴),但它在if条件内正常工作,print不显示任何内容,实际上似乎被中断,因为明确跳过了换行符.为什么行为改变了?
您不能声明void变量:
void fn() {
void a; // ill-formed
}
Run Code Online (Sandbox Code Playgroud)
但这编译为:
void fn() {
void(); // a void object?
}
Run Code Online (Sandbox Code Playgroud)
什么void()意思 有什么用?为什么void a;格式不正确,但void()可以?
void fn() {
void a = void(); // ill-formed
}
Run Code Online (Sandbox Code Playgroud) Perl方法通常以my $self = shift;并且随后用于$self引用它是方法的对象开始.
sub foo {
my $self = shift;
$self->method;
...
return $self->{_foo}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是$_[0]直接使用而不是复制$_[0]到 $self:
sub foo {
$_[0]->method;
...
return $_[0]->{_foo}
}
Run Code Online (Sandbox Code Playgroud)
现在,什么更有效(更快):
将内存分配给一个新变量$self,获取列表的第一项@_,并在每次调用一个方法时将该值复制到该变量;
每次使用时获取数组的第一项$_[0]?
如果在类中声明公共变量,则可以从也是该类成员的任何函数中修改该变量.
如果在函数内声明变量,则其范围不会超出函数的范围.
那么公共类变量本质上是一个全局变量,可以被类的任何成员访问和更改吗?
如果是这样的话,全局变量和公共变量之间有什么区别?
我做了一个名为的课程cell.在这个类中有一个cell指针数组.标题看起来像这样:
class cell
{
public:
cell();
cell *c[8];
void creatcells();
virtual ~cell();
..
}
Run Code Online (Sandbox Code Playgroud)
并且cpp文件看起来像这样:
cell::cell()
{
//ctor
for(int i=0;i<8;i++)
{
c[i]=NULL;
}
}
void cell::creatcells()
{
cell c1,c2,c3,c4,c5,c6,c7,c8;
c[0]=&c1;
c[1]=&c2;
c[2]=&c3;
c[3]=&c4;
c[4]=&c5;
c[5]=&c6;
c[6]=&c7;
c[7]=&c8;
}
cell::~cell()
{
for(int i=0; i<8; i++)
{
if (c[i]!=NULL)
{
delete c[i];
}
}
delete[] c;
}
Run Code Online (Sandbox Code Playgroud)
但每次程序结束时,都会崩溃,为什么?
我试过没有if (c[i]!=NULL),但这没有帮助.只有没有for循环,代码才能完美结束,但我知道这也必须删除.我想我正确地写了析构函数,不是吗?
我写了这个小函数:
int mayor(int n1, int n2, int n3, int n4, int n5) {
int mayor = n1;
for(int *p=&n2; p<=&n5; ++p)
mayor = *p;
return mayor;
}
Run Code Online (Sandbox Code Playgroud)
能够保证所有包含该内存块n1到n5是连续的?既然我得到了预期的回报值,我希望如此,但我想知道这是否安全.
c parameter-passing calling-convention memory-layout contiguous
c++ ×3
perl ×2
c ×1
contiguous ×1
crash ×1
destructor ×1
difference ×1
performance ×1
return-value ×1
scope ×1
self ×1
void ×1