【问题标题】:Unable to change private variable's content无法更改私有变量的内容
【发布时间】: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


    【解决方案1】:

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

    一个用于设置成员变量的对象(通过getPlayersNames 函数),另一个不相关的对象用于打印一组不同的变量。

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

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

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

    【讨论】:

    • 谢谢,成功了!还有一个问题,为什么将变量设为静态会使它们能够被其他对象使用?我以为 static 只声明了一次变量。
    • @Leviathan 一个static 成员变量存在并且在一个类的所有实例之间共享​​>
    • @Leviathan 请将其设置为答案...如果不是,Joachim 将不会因此获得荣誉。
    • 对不起,我是堆栈溢出的新手,我现在将其标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多