我是 C++ 的新手,正在尝试使用动态内存创建一些基本的对象。我将一个 int 参数传递给一个方法,它正在改变全局变量的值。我认为这与我为新对象分配内存的方式有关,我不能让它以任何其他方式编译。
int main () {
int inp;
CRectangle rectb (2,2);
cout << "enter number of items to add" << endl;
cin >> inp; // let's say inp = 7
rectb.addItemsArray(inp);
cout << "inp after adding items: " << inp << endl; // inp is now 1.
}
头文件:
class CRectangle {
int width;
int height;
item *items[]; // SOLUTION: change this line to "item *items"
int input;
public:
CRectangle (int,int);
int addItemsArray(int);
int area () { return (width*height); }
int get_items(int);
};
-和-
class item {
int foo;
char bar;
public:
//SOLUTION add "item ();" here (a default constructor declaration without arguments)
item (int, char);
int get_foo();
char get_bar();
};
方法:
int CRectangle::addItemsArray(int in) {
cout << "value of in at begginning:" << in << endl; //in = 7
int i;
i = 0;
//SOLUTION: add "items = new item[in];" on this line.
while (i < in) {
items[i] = new item(1, 'z'); //SOLUTION: change this line to "items[i] = item(1, 'z');"
i++;
}
cout << "value of in at end " << in << endl; //in = 7
return 1;
}
有时我会遇到总线错误或段故障。有时它会像 2 或 3 这样的较小数字按预期工作,但并非总是如此。
任何帮助将不胜感激。
编辑(CRectangle 的构造函数):
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
(项目的构造函数):
/* SOLUTION add default item constuctor
item::item() {
foo = 0;
bar = 'a';
}
*/
item::item(int arg, char arg2) {
foo = arg;
bar = arg2;
}