Here is a class, which is basically an array of numbers on which I want to perform some operations.
这是一个类,它基本上是一个数字数组,我想在其上执行一些操作。
class MyClass {
public:
MyClass() { //constructor
int * array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = i*i;
}
} //end constructor
int displayIthElement(int i) {
return array[i];
}
}
I get: error, identifier "array" is undefined in the displayIthElement function. It's as if the array array stops existing outside of the constructor function, which makes no sense. What is the problem?
我得到:error, displayIthElement函数中没有定义标识符"array"。这就好像数组数组在构造函数函数之外停止了存在,这毫无意义。这个问题是什么?
Thank you very much.
非常感谢。
1 个解决方案
#1
5
It's as if the array array stops existing outside of the constructor function, which makes no sense.
就好像数组停止存在于构造函数之外,这是没有意义的。
Actually, it's the only behavior that makes any sense at all... this is how the language works.
事实上,这是唯一有意义的行为……这就是语言的工作原理。
array
is a local variable declared and defined in your constructor. When the constructor exits the pointer variable is destroyed, and you leak the memory it refers to. Memory allocated with new
or new []
always requires a corresponding delete
or delete []
before its referent goes out of scope. Always.
数组是在构造函数中声明和定义的一个局部变量。当构造函数退出时,指针变量将被销毁,并且您泄漏了它所引用的内存。使用new或new[]分配的内存在其引用超出范围之前总是需要相应的删除或删除[]。总是这样。
array
should be a member of the class. You're learning, so it's a good idea to figure out how dynamic memory handling works, but in the future, prefer a safe container (i.e., std::unique_ptr
, std::vector
, etc.) which handles allocation and deallocation for you.
数组应该是类的成员。你正在学习,所以弄清楚动态内存处理是如何工作的是一个好主意,但是在将来,你更喜欢安全的容器(例如:它为您处理分配和重分配。
class foo {
public:
foo() {
array = new int[length];
for(int i = 0; i < length; i++) {
array[i] = i*i;
}
}
private:
int *array; // when does this get deallocated? Look up RAII
};
#1
5
It's as if the array array stops existing outside of the constructor function, which makes no sense.
就好像数组停止存在于构造函数之外,这是没有意义的。
Actually, it's the only behavior that makes any sense at all... this is how the language works.
事实上,这是唯一有意义的行为……这就是语言的工作原理。
array
is a local variable declared and defined in your constructor. When the constructor exits the pointer variable is destroyed, and you leak the memory it refers to. Memory allocated with new
or new []
always requires a corresponding delete
or delete []
before its referent goes out of scope. Always.
数组是在构造函数中声明和定义的一个局部变量。当构造函数退出时,指针变量将被销毁,并且您泄漏了它所引用的内存。使用new或new[]分配的内存在其引用超出范围之前总是需要相应的删除或删除[]。总是这样。
array
should be a member of the class. You're learning, so it's a good idea to figure out how dynamic memory handling works, but in the future, prefer a safe container (i.e., std::unique_ptr
, std::vector
, etc.) which handles allocation and deallocation for you.
数组应该是类的成员。你正在学习,所以弄清楚动态内存处理是如何工作的是一个好主意,但是在将来,你更喜欢安全的容器(例如:它为您处理分配和重分配。
class foo {
public:
foo() {
array = new int[length];
for(int i = 0; i < length; i++) {
array[i] = i*i;
}
}
private:
int *array; // when does this get deallocated? Look up RAII
};