我遇到了一个问题,我已经一周没有找到答案了。我有一个动态数组类,它有一个向它添加字符串值的方法。它应该代表您可以添加项目的库存。但是,当我稍后在 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/