c++ - 在方法中更改类的私有(private)值而不将更改返回给 main()

标签 c++ c++11

我遇到了一个问题,我已经一周没有找到答案了。我有一个动态数组类,它有一个向它添加字符串值的方法。它应该代表您可以添加项目的库存。但是,当我稍后在 main() 中尝试为类元素“backpack”调用打印方法时,我发现在方法中对类元素的私有(private)值所做的更改没有“更新”。我认为这可能是由于引用问题导致的问题,但我已经看到当类不在不同模块中时这项工作。

我的“背包”模块打印和添加方法:

 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;
}
}

主要():

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没有析构函数(意味着内存泄漏),或者没有正确的复制构造函数我希望您会遇到“双重释放”问题。 (阅读“三法则”。)

关于c++ - 在方法中更改类的私有(private)值而不将更改返回给 main(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41123925/

相关文章:

c++ - char数组编译错误

使用 stringstream::str() 更新后,C++ stringstream 无法正常工作

c++ - 从 size_t 到 wchar_t 的转换需要缩小转换

c++ - 从函数返回 shared_ptr 的取消引用值

c++ - 在模板参数的方法中添加类型转换时出现 clang 错误

c++ - 使用C++ 11时列表中的编译错误

c++ - 循环内的尾递归如何工作?

c++ - 为什么我解决N个皇后区问题的回溯解决方案不起作用?

c++ - 我如何将 system_clock::now() 与 c++20 中的本地时间进行比较?

c++ - 从可连接的线程中销毁线程的对象