Access成员字段与本地变量(或参数)具有相同的名称 [英] Access member field with same name as local variable (or argument)
本文介绍了Access成员字段与本地变量(或参数)具有相同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下代码段:
struct S
{
S(const int a)
{
this-> a = a; // option 1
S :: a = a; // option 2
}
int a;
};
选项1相当于选项2?有一种形式比另一种形式更好的情况吗?选项1相当于选项2,但是选项1不适用于静态的选项2。数据成员
EDITED:可以使用此指针访问静态数据成员。但是this->成员不会在静态函数中工作。但选项2将在静态函数中使用静态成员。
例如:
struct S
{
static void initialize(int a)
{
// this-> a = a;编译错误
S :: a = a;
}
static int a;
};
int S :: a = 0;
Consider following code snippet:
struct S
{
S( const int a )
{
this->a = a; // option 1
S::a = a; // option 2
}
int a;
};
Is option 1 is equivalent to option 2? Are there cases when one form is better than another? Which clause of standard describes these options?
解决方案
option 1 is equivalent to option 2, but option 1 will not work for a static data member
EDITED: static data members can be accessed with this pointer. But this->member will not work in static function. but option 2 will work in static function with static member
Eg:
struct S
{
static void initialize(int a)
{
//this->a=a; compilation error
S::a=a;
}
static int a;
};
int S::a=0;
这篇关于Access成员字段与本地变量(或参数)具有相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文