<分区>
我有一个类使用 vector 来存储一组具有无符号长整数的对象。对该类的操作之一是通过将它与另一个 u_long 进行 OR 运算来更改元素的存储 u_long。
如果我在执行 OR 后立即 cout
,它表明数字已更改。但是,如果我返回并cout
vector 中的元素,它不会显示已进行任何更改。我在这里缺少什么?
类定义
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