Monday 15 August 2011

c++ - Resolving shadowing of local scope with class scope -



c++ - Resolving shadowing of local scope with class scope -

the scope resolution operator can used resolve name clashes between class scope , global scope (as shown in initialization of g::sum below). possible resolve similar clashes between local class' scope , surrounding local scope (as (not) shown in initialization of l::sum below)?

#include <cassert> int clash_g = -332; struct g { int clash_g = 333; int sum = clash_g + ::clash_g; }; int main() { int clash_l = -332; struct l { int clash_l = 333; int sum = clash_l + clash_l; }; assert(g().sum == 1); assert(l().sum == 666); // want 1, in g::sum }

first of clash_l -332 not 333 reply cannot resolve such clash because struct a datatype declaration , main function local scope not global scope can't address variable in main function struct even if have different names

edit: still can't access "surrounding local scope" ask because you're in struct definition new datatype definition work around declare static variable in main

static int x = -332

and phone call in struct

int sum = clash_l + x;

c++ scope

No comments:

Post a Comment