【发布时间】:2019-11-12 19:52:41
【问题描述】:
我有一个类,它使用向量来存储一组具有无符号长整数的对象。该类的操作之一是通过将元素与另一个 u_long 进行 OR-ing 来更改存储的元素 u_long。
如果我在执行 OR 后立即cout,则表明号码已更改。但是,如果我返回并 cout 向量中的元素,则不会显示进行了任何更改。我在这里错过了什么?
类定义
class ULBox {
public:
ULBox(std::string s) {
label = s;
};
~ULBox(){};
std::string getLabel(){
return label;
};
void setNumber(unsigned long n) {
number |= n;
};
unsigned long getNumber(){
return number;
}
private:
std::string label;
unsigned long number;
};
class BoxList {
public:
BoxList() {};
~BoxList() {};
bool addBox(std::string label) {
ULBox newBox(label);
boxes.push_back(newBox);
return true;
};
bool updateBoxNums(unsigned long num) {
int i = 1;
for(auto box: boxes) {
box.setNumber(num+i);
std::cout << box.getNumber() << std::endl;
i++;
};
return true;
};
void printBoxes() {
for(auto box: boxes) {
std::cout << box.getLabel() << ": " << box.getNumber() << std::endl;
};
};
private:
std::vector<ULBox> boxes;
};
主要功能
int main(void) {
BoxList b_list;
b_list.addBox("first");
b_list.addBox("second");
b_list.addBox("third");
b_list.updateBoxNums(2);
b_list.printBoxes();
};
输出 output displaying 3, 4, 5 and then 0s where there should be another 3, 4, 5
【问题讨论】: