Access member field with same name as local variable (or argument)

寵の児 提交于 2019-12-12 09:41:19

问题


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 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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!