使用此指针区分成员数据和参数
这是区分成员数据和参数的实际有用策略……让我们举个例子:
// 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