Oke,
I got a function in a class, this function takes the arguements:
testfunc(int a,int b);
Now these variables (int a,int b) exists in the class as well, how
can i adress the variables in the class?
Oke,
I got a function in a class, this function takes the arguements:
testfunc(int a,int b);
Now these variables (int a,int b) exists in the class as well, how
can i adress the variables in the class?
ClassName::MemberName from within the member function
If the function and members are of the same class then you don't have to do anything special, just use the members in the function like you would anywhere else, unless the members and function arguments have the same names. If that's the case then you could have problems, so be explicit.
Code:#include <iostream> #include <string> using namespace std; class test { int a, b; public: void function(int a, int b) { this->a = a; this->b = b; } void print() { cout<< a <<endl<< b <<endl; } }; int main() { test t; t.function(1, 2); t.print(); }
*Cela*
yeah, use the 'this->' variable
My Avatar says: "Stay in School"
Rocco is the Boy!
"SHUT YOUR LIPS..."
and if you dont use this it will search for the variable
in the class first and then in the passed arguments?
No, I don't think so - it's a matter of SCOPE it will probably just use the local variables.
My Avatar says: "Stay in School"
Rocco is the Boy!
"SHUT YOUR LIPS..."
hmm, so 'this->' is a way to assure that it uses the local function
variables, and how can i assure it uses the class variables?
No, you're confused.Originally posted by Travis Dane
hmm, so 'this->' is a way to assure that it uses the local function
variables, and how can i assure it uses the class variables?
the keyword 'this' represents a pointer to the object you are currently in, so
this->membername
says "the member of the current object called membername"
In other words, that refers to the MEMBER not the variable local to the function. To use the one local to the function you just use the variable name -- the most local variable with the same name is the one that's used.
The other way you can access the object's member (IE the one not passed to the function), is how I mentioned with the scope resolution operator
ClassName::MemberName
which will have the same end result as
this->MemberName
I'm still a little confused,
How would i accomplish something like this
Code:class test { public: void outputsomething(int a); private: int a; }; void outputsomething(int a) { cout << a; // output the passed var cout << a; // output the class's var }
Code:class test { public: void outputsomething(int a); private: int a; }; void test::outputsomething(int a) { cout << a; // output the passed var cout << this->a; // output the class's var }
My Avatar says: "Stay in School"
Rocco is the Boy!
"SHUT YOUR LIPS..."
k,got i now, thx