无法更改私有变量的内容

Unable to change private variable's content

main.cpp :

#include <iostream>
#include <string>
#include "Players.h"
using namespace std;

int main ()
{
    cout << "**** Welcome to Leviathan's first TicTacToe Game! ****\n\n";
    Players getNamesobject;
    Players printNamesobject;
    getNamesobject.getPlayersNames();
    printNamesobject.printPlayersNames();

}

Players.h:

#ifndef PLAYERS_H
#define PLAYERS_H


class Players
{
    public:
        void getPlayersNames();
        void printPlayersNames();
    private:
        std::string _player1Name;
        std::string _player2Name;
};

#endif // PLAYERS_H

Players.cpp :

#include <iostream>
#include <string>
#include "Players.h"
using namespace std;

void Players::getPlayersNames()
{
    string p1,p2;
    cout << "Enter player 1 name : ";
    cin >> p1;
    cout << "\nEnter player 2 name : ";
    cin >> p2;
    _player1Name = p1;
    _player2Name = p2;
}

void Players::printPlayersNames()
{
    cout << "Alright " << _player1Name << " and " << _player2Name <<", the game has begun!\n\n";
}

当我 运行 执行此操作并输入两个名称时,_player1Name 和 _player2Name 变量不会更改。我试过手动为它们设置一个字符串,它们可以正常打印。谁能解释这里出了什么问题?好像 getPlayerNames 函数不能改变私有变量?

那是因为你有两个不同的对象

一个是你在其中设置成员变量的(通过 getPlayersNames 函数),另一个是你用来打印不同变量集的不相关对象。

您应该有一个对象,并对该单个对象调用 getPlayersNamesprintPlayersNames。喜欢

Players playersObject;
playersObject.getPlayersNames();
playersObject.printPlayersNames();

您创建的 Players 对象的每个实例都有自己的一组成员变量,这些成员变量与该单个对象相关联,成员变量不在对象之间共享(除非您将它们设为 static ).