【问题标题】:Properly Store Object in Vector在向量中正确存储对象
【发布时间】:2015-09-07 14:59:39
【问题描述】:

我是 C++ 新手,这是我第一次发帖(灾难的秘诀)。我花了大约一天的时间试图解决我的问题/疑问,同时在论坛上找不到容易识别的解决方案。有可能我的问题已经被问到或者已经发布了解决方案,但我忽略了它或误解了它。类似的帖子存在 here,但我不清楚如何处理这些信息。

我将提供此代码要点的简明高级摘要。然后,我将询问我无法找到答案的具体问题,然后我将按照我编写的代码进行操作。

摘要:我正在创建一个程序来帮助为游戏记账。游戏可能有任意数量的玩家,每个玩家都有一小部分属性/成员(例如 playerName、playerAllegiance 等),它们是 Player 类/对象的元素。首先要求用户输入每个玩家的名字(enteredName),程序必须为每个输入的名字创建一个新的 Player 对象。这似乎可以通过动态数组适当地处理,因此我选择使用一个向量(称为 playerIndex)来存储每个 Player 对象。 for 循环允许用户输入名称,每个名称实例化一个新的 Player 对象,该对象将使用 vector::push_back 存储(复制?)到 playerIndex 中。在 for 循环结束时,应该给用户留下一个 Player 对象向量,每个 Player 对象在其 playerName 成员中存储一个名称。

问题/问题:在监控上述 for 循环内的向量时,代码似乎可以正常工作。在用户输入第 N 个玩家的名字后,程序立即使用 Player 类函数 getPlayerName() [实际代码:playerIndex[playerCounter].getPlayerName()] 吐出存储在 playerIndex 的第 N 个元素中的 playerName 字符串。一旦用户输入一个空白的 playerName(即按 enter 而不输入名称),则表明用户已输入所有玩家名称,因此 for 循环终止。在这个循环之后,一个旨在输出存储在 playerIndex 中的每个 Player 对象的 playerName 的循环不会输出预期的名称。我不知道为什么会这样,但根据我对构造函数的了解,我猜这与 Player 类的复制或移动构造函数有关。谁能清楚地解释如何处理这个问题?我担心我可能会犯一个非常愚蠢的新手错误和/或误解 C++ 的一个关键概念。

代码:此代码已被裁剪/简化以尽可能清晰。例如,Player 类显示为只有一个成员 (playerName),而在原始代码中,它有四个或五个其他成员。

//HeaderPlayerClass.hpp
#include <iostream>
#include <string>

#ifndef PLAYERCLASS_HPP
#define PLAYERCLASS_HPP

using std::string;

class Player {
    private:
        string *playerName;

    public:
        Player();
        Player(string);
        ~Player();
        string getPlayerName();
};

#endif




//PlayerClass.cpp
#include "HeaderPlayerClass.hpp"
#include <iostream>
#include <string>

using std::string;

Player::Player() {
    playerName = new string;
}

Player::Player(string enteredName) {
    playerName = new string;    
    *playerName = enteredName;
}

Player::~Player() {
    delete playerName;
}

string Player::getPlayerName() {
    return *playerName;
}





//main.cpp
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include "HeaderPlayerClass.hpp"

using std::cin;
using std::cout;
using std::string;
using std::vector;

int main(int argc, char** argv) {

    string buffer;
    vector<Player> playerIndex;

    int playerCounter = 0;

    for(;;) {
        if(playerCounter==0) {
            cout << "\nEnter player name and press enter; leave blank and press enter to continue.\n";
        }

        cout << "\nPlayer " << playerCounter+1 << ":";
        getline(cin, buffer);

        if(buffer == "esc") {
            cout << "PROGRAM EXITED BY USER\n";
            return 0;
        }

        if(buffer.empty()) {
            break;
        }

        playerIndex.push_back(Player(buffer));
        cout << "Player " << playerCounter+1 << "'s name:" << playerIndex[playerCounter].getPlayerName() << "\n";

        ++playerCounter;
    }

    for(int ii = 0 ; ii < playerIndex.size() ; ii++) {
        cout << "\nThis should display player " << ii+1 << "'s name:" << playerIndex[ii].getPlayerName();
    }

    return 0;
}

【问题讨论】:

    标签: c++ object vector


    【解决方案1】:
    class Player {
        private:
            string *playerName;
    

    不存储指向字符串的指针,存储字符串本身

    class Player {
        private:
            string playerName;
    

    构造函数

    Player::Player() {
        playerName = new string;
    }
    

    如果您存储字符串本身,这是不必要的 - 默认构造函数会为您初始化它。

    问题从这里开始——除非你仔细编写析构函数,否则这会让你容易受到内存泄漏的影响

    Player::Player(string enteredName) {
        playerName = new string;    
        *playerName = enteredName;
    }
    

    所有你需要的,如果你存储字符串本身:

    Player::Player( const string& enteredName)
    : playerName ( enteredName )
    {}
    

    你的构造函数真的很可怕。当您存储字符串本身时,只需将内容留给默认析构函数

    Player::~Player() {
        delete playerName;
    }
    

    接下来,你太努力了,保持自己的柜台。 std::vector 维护自己的计数并使用

    playerIndex.size()
    

    将节省麻烦和错误

    【讨论】:

    • 构造函数应该使用初始化,而不是赋值。 Player::Player( const string&amp; enteredName) : playerName(enteredName) {}
    • 这一切都说得通(包括列表初始化),但我仍然不清楚何时适合使用“new”,尤其是在类的上下文中。假设 enterName 是一个 int 而不是一个字符串;由于 int 没有像字符串这样的默认构造函数,构造函数是否需要实现“new int”(类似于我在发布的代码中尝试执行的操作)?
    • @roc645 没有“new int”这样的东西,所以我的建议是不要使用它!说真的,int 的初始化留给编译器,许多但不是全部将它设置为零。因此,为了安全和便携,您将始终必须为 int 分配一个值
    • @ravenspoint:当然有new int这样的东西!只是你很少或几乎从不需要它。和零初始化无关;这是语言的一个几乎正交的方面。此外,赋值和初始化是完全不同的事情。您对 OP 的建议可能在精神上是好的,但是您混淆了太多东西以及您描述它们的方式,您的评论在技术上不准确或错误。
    • @roc645:C++ 对于初学者来说确实有点困难。我的建议是在你觉得有必要之前不要使用动态分配。在现代 C++ 中,这种情况很少发生,因为所有标准类都在其实现中隐藏了所有动态分配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多