0

a question about Class

public: Point(int xx=0,int yy=0) { x=xx; y=yy; } question:I think "x=xx;y=yy" is useless.Can I type these codes like the flowing? public: Point(intx=0,int y=0) { }

24th Nov 2016, 12:47 AM
劳英勇
劳英勇 - avatar
1 Resposta
+ 2
The reason different variables are used for "setters" (class member functions that set the value for member variables within the same class) is because of conflicts. If you had a private variable X, and the parameter of the setter function as X, then both of those X variables would be in scope, so C++ doesn't know what X you are referring to. I agree with you, I do not like using different variable names in the parameters of setter functions. I find it unnecessary and messy. We use the this pointer to tackle this. The this pointer is used to refer to the current object in use. This written example may help you understand a bit better: class Person { public: void setAge(int age) { this->age = age; } int getAge() { return age; } private: int age; }; int main() { Person bob; bob.setAge(21); cout << "Bob is " << bob.getAge() << " years old!"; }
24th Nov 2016, 2:37 AM
Cohen Creber
Cohen Creber - avatar