在方法中更改类的私人价值不会将更改返回main()

Changing a private value of a class in method not returning the changes to main()

本文关键字:返回 main 方法      更新时间:2023-10-16

我遇到的问题现在我一周没有找到答案。我有一个动态的数组类,它具有将字符串值添加到其的方法。它应该代表您可以将项目添加到的库存。但是,我发现,当我试图在Main()中呼叫"背包"类" backpack"的print方法时,方法中对类元素的私人值进行的更改并未"更新"。我认为这可能是一个问题,这可能是一个问题,但是当一堂课没有参加其他模块时,我已经看到这项工作。

我的"背包"模块打印并添加方法:

 const int INITIAL_SIZE = 5;
 Inventory::Inventory():
        array_(new string[INITIAL_SIZE]),
        max_space_(INITIAL_SIZE),
        used_space_(0) {}
 void Inventory::add(string item){
if ( size() == max_space_ ) {
    string* new_array = new string[2 * max_space_];
    for ( int i = 0; i < size(); ++i ) {
        new_array[i] = array_[i];
    }
    delete [] array_;
    array_ = new_array;
    max_space_ = 2 * max_space_;
}
array_[used_space_] = item;
++used_space_;
}
void Inventory::print() {
for ( int i = 0; i < size(); ++i ) {
    cout << array_[i] << endl;
}
}

main():

Inventory inv;
string input;
while (cout << "input> "
        and getline(cin,input)){
add_to_bag(input,inv);

因此,当您提供新内容时,您将库存重置。函数add_to_bag();是:

  void add_to_bag(string input, Inventory inv){
  const string WHITESPACE1_REGEX = "[[:space:]]*";
  const string WHITESPACE2_REGEX  = "[[:space:]]+";
  const string WORD_REGEX                      = "[[:alpha:]_]+";
  const string LINE_REGEX =
      WHITESPACE1_REGEX +
      WORD_REGEX +
      "(" +
      WHITESPACE2_REGEX +
       WORD_REGEX +
      ")*" +
      WHITESPACE1_REGEX;
regex line_reg(LINE_REGEX);
regex word_regex(WORD_REGEX);
string line = input;
    if ( regex_match(line, line_reg) ) {
        sregex_iterator iter(line.begin(), line.end(), word_regex);
        sregex_iterator end;
        while ( iter != end ) {
            inv.add(iter->str());
            ++iter;
        }
    } else {
        cout << "Error: unknown inventory contents." << endl;
    }
}

您的问题是:

    void add_to_bag(string input, Inventory inv);

您将Inventory对象的复制传递给add_to_bag。您修改了该副本...然后被扔掉。修复程序是通过参考通过:

    void add_to_bag(string input, Inventory &inv);

顺便说一句,在现实代码中,我强烈建议使用std::vector<std::string>,而不是"滚动自己"。您在这里有很多棘手的异常处理问题 - 除非Inventory没有驱动器(意味着内存泄漏),或者确实有一个正确的复制构造函数,我希望您会遇到" double Free Free"问题。(阅读有关"三个规则"。)

设计类的简单方法如下:

class Inventory {
private:
    std::vector<std::string> items_;
public:
    Inventory(){}
    ~Inventory(){}
    void addItem( const std::string& item ) {
       items_.push_back( item );
    }
    void printInventory() const {
        int idx = 0;
        for (; idx < items_.size(); ++idx ) {
            std::cout << items_[idx] << std::endl;
        }     
    }
    void clearInventory() {
        items_.clear();
    }
};

,就您的问题而言,马丁·邦纳(Martin Bonner)已经通过修改副本的修改以及之后的删除以及内存管理的其他问题来回答。