C++ class variables as method parameters?
When we are defining the method of a class, is it alright if we use th开发者_如何学Ce class variables (whether public or private) as the method's-parameters?
In other words which one would be "more correct?"
Having defined ,
class myclass{
public:
int x, y;
double foo(int, int, int);
private:
int z;
}
is this ok
double myclass::foo(int x, int y, int z) {/* Blah Blah */}
or
double myclass::foo(int xx, int yy, int zz){x=xx; y=yy; z=zz /* Blah Blah*/}
These two:
double myclass::foo(int x, int y, int z) {/* Blah Blah */}
double myclass::foo(int xx, int yy, int zz){x=xx; y=yy; z=zz /* Blah Blah*/}
Do not do the same thing. The first one declares a function who's arguments are called x
, y
, and z
. Because they are named the same as class-scoped variables, they hide the class-scoped variables. To access the hidden members inside "Blah Blah", you would have to use this->x
and so forth.
This does not cause the arguments to be forwarded directly into the values of the members of the class.
Either way is fine. If you need to disambiguate, just use the this
keyword:
this->x = x;
It is "OK" in the same way that you are allowed open new scopes and hide names:
int a;
void foo()
{
int a;
{
int a;
// how do we refer to the other two now?
}
}
If your function definition uses the same symbols for the argument variables as are already used in the class scope, then the functions-scope symbol hides the one in the outer scope. You can sometimes disambiguate (e.g. with ::a
in my example, or this->x
in yours), but as my example shows, you can always hide a variable so much that it's no longer addressable.
In short, don't make your life hard, and stick to a sensible naming scheme that avoids unnecessary ambiguity. Programming is hard enough without tying your hands to your ankles.
精彩评论