无法更改私人变量的内容

时间:2016-06-28 11:30:48

标签: c++ class variables object private

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函数无法更改私有变量?

1 个答案:

答案 0 :(得分:7)

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

您可以在(通过getPlayersNames函数)中设置成员变量,以及用于打印不同变量集的另一个不相关对象。

您应该有一个对象,并在该单个对象上调用getPlayersNamesprintPlayersNames。像

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

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