Lev*_*han 2 c++ variables private class object
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();
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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";
}
Run Code Online (Sandbox Code Playgroud)
当我运行它并输入两个名称时,_player1Name和_player2Name变量不会被更改.我已经尝试手动设置它们并正常打印.任何人都可以解释这里有什么问题吗?看来getPlayerNames函数无法改变私有变量?
这是因为你有两个不同的对象!
您可以在(通过getPlayersNames函数)中设置成员变量,以及用于打印不同变量集的另一个不相关对象.
你应该有一个单独的对象,并调用getPlayersNames与printPlayersNames该单个对象.喜欢
Players playersObject;
playersObject.getPlayersNames();
playersObject.printPlayersNames();
Run Code Online (Sandbox Code Playgroud)
Players您创建的对象的每个实例都有自己的一组成员变量,这些变量与该单个对象相关联,成员变量不在对象之间共享(除非您创建它们static).