【发布时间】:2016-10-30 17:05:32
【问题描述】:
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 函数不能更改私有变量?
【问题讨论】:
标签: c++ class variables object private