使用此指標區分成員資料和引數
這是區分成員資料和引數的實際有用策略……讓我們舉個例子:
// Dog Class Example
#include <iostream>
#include <string>
using std::cout;
using std::endl;
/*
* @class Dog
* @member name
* Dog's name
* @function bark
* Dog Barks!
* @function getName
* To Get Private
* Name Variable
*/
class Dog
{
public:
Dog(std::string name);
~Dog();
void bark() const;
std::string getName() const;
private:
std::string name;
};
Dog::Dog(std::string name)
{
/*
* this->name is the
* name variable from
* the class dog . and
* name is from the
* parameter of the function
*/
this->name = name;
}
Dog::~Dog(){}
void Dog::bark() const
{
cout << "BARK" << endl;
}
std::string Dog::getName() const
{
return this->name;
}
int main()
{
Dog dog("Max");
cout << dog.getName() << endl;
dog.bark();
}
你可以在建構函式中看到我們執行以下操作:
this->name = name;
在這裡,你可以看到我們正在從類 Dog(this-> name)中將引數名稱分配給私有變數的名稱。
要檢視上面程式碼的輸出: http : //cpp.sh/75r7