问题
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?
回答1:
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;
回答2:
Have you tried this option?
struct S
{
S(int a) : a(a) { }
int a;
};
Have a look at the following:
12.6.2 Initializing bases and members
[12] Names in the expression-list or braced-init-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified. [ Example:
class X {
int a;
int b;
int i;
int j;
public:
const int& r;
X(int i): r(a), b(i), i(i), j(this->i) { }
};
initializes
X::r
to refer toX::a
, initializesX::b
with the value of the constructor parameteri
, initializesX::i
with the value of the constructor parameteri
, and initializesX::j
with the value ofX::i
; this takes place each time an object of classX
is created. — end example ] [ Note: Because the mem-initializer are evaluated in the scope of the constructor, thethis
pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. — end note ]
回答3:
Both forms are identical unless a
is a virtual function. I'd
prefer this->a
, because it does what I usually want even if
a
is a virtual function. (But isn't it better to avoid the
name clash to begin with.)
来源:https://stackoverflow.com/questions/22832001/access-member-field-with-same-name-as-local-variable-or-argument