Access member field with same name as local variab

2019-05-06 23:09发布

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?

3条回答
该账号已被封号
2楼-- · 2019-05-06 23:31

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 to X::a, initializes X::b with the value of the constructor parameter i, initializes X::i with the value of the constructor parameter i, and initializes X::j with the value of X::i; this takes place each time an object of class X is created. — end example ] [ Note: Because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. — end note ]

查看更多
男人必须洒脱
3楼-- · 2019-05-06 23:51

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.)

查看更多
Luminary・发光体
4楼-- · 2019-05-06 23:52

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;
查看更多
登录 后发表回答