C++"this"类属性

Mic*_*lec 1 c++ pointers class this

//C++ Made Easy HD 26 - Introduction to Classes
//Michael LeCompte

#include <iostream>
#include <string>

using namespace std;


class Player {
public:
    Player() {
        cout << "1st overload" << endl;
    }

    Player(int Health){
        cout << "2nd overload" << endl;
        this->health = Health;
    }

    Player(int Health, int attPow){
        cout << "3nd overload" << endl;
        this->health = Health;
        attackPower = attPow;
    }

    ~Player() {
        cout << "Player instance destroyed" << endl;
    }

    //Mutators
    void setHealth(int val) {
        health = val;
    }

    void setAttPow(int val) {
        attackPower = val;
    }

    void setDef(int val) {
        defense = val;
    }

    void setXp(int val) {
        xp = val;
    }

    //Accessors
    int healthVal() {
        return health;
    }

    int attPowVal() {
        return attackPower;
    }

    int defVal() {
        return defense;
    }

    int xpVal() {
        return xp;
    }

private:
    int health;
    int attackPower;
    int defense;
    int xp;
};


int main() {
    Player player[4] = {Player(2, 5), Player(65, 2), Player(2), Player(1)};
    cout << player[0].healthVal() << endl;
    cout << player[1].healthVal() << endl;
    cout << player[2].healthVal() << endl;

    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

从上面的代码中我关注的是this->health = Health线条.我想知道为什么我需要使用this->health而不是health = Health.我知道它与我正在Player用数组创建新对象这一事实有关(我正在做一个教程).我只是不明白它为什么这么做我必须使用this->或如何工作.谢谢.

WoJ*_*oJo 6

你不要用这个.health = Health;将工作.但正确的方法是使用初始化:

Player(int Health) : health(Health) {
  // constrcutor code
}
Run Code Online (Sandbox Code Playgroud)