J'essayais de réviser mes concepts de programmation Orienté Objet. En passant par cet exemple C++ de base here, j'ai vu que le mot-clé this->
n'a pas été utilisé lors de la définition des valeurs pour les variables membres. J'ai ensuite modifié ce programme pour utiliser le mot-clé this
. De manière surprenante, les deux fonctionnent (this et this).Quand utiliser `this` dans ce contexte en C++
#include <iostream> // for cout and cin
class Cat // begin declaration of the class
{
public: // begin public section
Cat(int initialAge); // constructor
Cat(const Cat& copy_from); //copy constructor
Cat& operator=(const Cat& copy_from); //copy assignment
~Cat(); // destructor
int GetAge() const; // accessor function
void SetAge(int age); // accessor function
void Meow();
private: // begin private section
int itsAge; // member variable
char * string;
};
// constructor of Cat,
Cat::Cat(int initialAge)
{
itsAge = initialAge;
string = new char[10]();
}
//copy constructor for making a new copy of a Cat
Cat::Cat(const Cat& copy_from) {
itsAge = copy_from.itsAge;
string = new char[10]();
std::copy(copy_from.string+0, copy_from.string+10, string);
}
//copy assignment for assigning a value from one Cat to another
Cat& Cat::operator=(const Cat& copy_from) {
itsAge = copy_from.itsAge;
std::copy(copy_from.string+0, copy_from.string+10, string);
}
Cat::~Cat() // destructor, just an example
{
delete[] string;
}
// GetAge, Public accessor function
// returns value of itsAge member
int Cat::GetAge() const
{
return itsAge;
}
// Definition of SetAge, public
// accessor function
void Cat::SetAge(int age)
{
// set member variable its age to
// value passed in by parameter age
itsAge = age;
}
// definition of Meow method
// returns: void
// parameters: None
// action: Prints "meow" to screen
void Cat::Meow()
{
cout << "Meow.\n";
}
// create a cat, set its age, have it
// meow, tell us its age, then meow again.
int main()
{
int Age;
cout<<"How old is Frisky? ";
cin>>Age;
Cat Frisky(Age);
Frisky.Meow();
cout << "Frisky is a cat who is " ;
cout << Frisky.GetAge() << " years old.\n";
Frisky.Meow();
Age++;
Frisky.SetAge(Age);
cout << "Now Frisky is " ;
cout << Frisky.GetAge() << " years old.\n";
return 0;
}
Ma question est, devrions-nous, ou ne devrait pas nous utiliser mot-clé this
dans ce contexte (lorsque vous définissez les valeurs des variables membres)? Merci!
Edit: Ou, est-ce une préférence personnelle comme mentionné here?
Comme vous l'avez découvert, cela n'a pas d'importance. C'est surtout un problème de style. Parfois, cela ajoute de la clarté pour le lecteur en expliquant que la variable est une variable membre. –
@BradS. Je peux me tromper ici, mais Java _mandate_ il? –
Préférence personnelle. A propos de la seule fois où vous devriez utiliser 'this' si vous aimez marcher sur le côté sauvage et utiliser les mêmes noms pour les paramètres et les variables membres. – user4581301