题
我正在尝试动态分配(它不像现在那样动态,但最终将是),用于对象 非常 简单的C ++程序。我是上课的新手,直到最近才开始与C ++一起玩,而C则留下了C。这是代码:
#include <iostream>
using namespace std;
class Test {
private:
int i;
public:
Test(int);
~Test();
void print();
};
Test::Test(int ii) { i = ii; }
Test::~Test() { i=0; cout << "deconstructor called...value of i= " << i << endl; }
void Test::print() { cout << "value of i= " << i << endl; }
int main()
{
Test a(10),*b,*c;
//a.print(); // this works
b = new Test(12);
//b->print(); // this works as well
for (int i=0; i<2; i++)
c = new Test(i);
c->print(); /* this shows that the value of i=1 .. should be 0? */
c[0].print(); /* as expected (I guess), this prints i=1 as well... [expected because c->print() shows i=1 also */
c[1].print(); /* shows value of i=0... */
//delete []c; /* this fails miserably, but `delete c` works, why :( */
}
我的许多混乱实际上都包含在代码本身中的评论中。我基本上是在试图拥有一个数组 C 数组的每个元素都是自身的对象。
评论中描述了我得到的代码的行为。
解决方案
也许我们应该看一下声明,扩展您:
Test a(10);
Test *b;
Test *c;
您已经将B和C定义为指控,但是您似乎希望C是一系列指向测试。您预定的C声明可能是:
Test **c;
您将初始化:
c = new Test*[2];
for (int i=0; i<2; i++)
c[i] = new Test(i);
以及您这样访问的内容:
c[0]->print();
c[1]->print();
其他提示
给定代码几乎没有严重的问题。
- 表演
new
上*b
但错过了delete
它。 - 你在覆盖
*c
几次for
循环,它将泄漏内存。从指针分配新的资源之前,请始终处理资源。 - 如果您要分配
new/new[]/malloc
然后,您必须使用指针delete/delete[]/free
分别。你没有维持的*c
(这就是为什么失败的原因)。
同样,除了学习动态分配外,还应注意STL容器,这为处理动态资源提供了更好的方法。例如 std :: vector.
for (int i=0; i<2; i++)
c = new Test(i);
以上代码泄漏内存。 c
只需指向循环迭代中最后构造的对象即可。
c-> print(); /*这表明i = 1 ..的值应该是0?
这里 c
指向构建的位置 new Test(1);
. 。因此,输出。
每一个 新的[ 应该伴随 删除[ 和 新的 和 删除. 。你不能同时互mix。
那是 delete[]
工作不是完全正常:您从不分配C作为数组,而是指针。您可以将数组的地址存储在指针中,仅此而已。我实际上想知道为什么C [1]究竟有效,因为您 for
循环只是在同一指针中反复存储指向新分配的对象(您没有填充数组!)。
delete c[];
仅删除起始元素。如果要删除该数组 dz delete c[]
在循环中
您未能为C分配内存并继续编码其错误,如何在不分配内存为指针变量的情况下获取输出?
据我所说,您已经为 *C多次分配了记忆
for (int i=0; i<2; i++)
c = new Test(i);
看看此代码,这将使一切清晰
for (int i=0; i<2; i++)
{ c = new Test(i); } /*see , here the loop goes for i=0; then
for i=1; which basically overwrites what c will have
i.e. finally c = new test(1); */
c->print(); /* works fine , gives value of i=1 */
c[0].print(); /* as expected , this prints i=1 as well... */
c[1].print(); /*clearly, it will give a garbage value */
delete c;
但是据我说,替换会更加好
for (int i=0; i<2; i++)
{ c = new Test(i); }
和
c = new Test(1); //as the previous code is doing the same in for loop but that was consuming more resources
因此,如果您希望输出为i = 0,然后i = 1,然后做 -
c = new int(0);
c->print(); /* works fine , gives value of i=0 */
c[0].print(); /* as expected , this prints i=0 as well... */
delete c;
c = new int(1);
c->print(); /* works fine , gives value of i=1 */
c[0].print(); /* as expected , this prints i=1 as well... */
delete c;
以上代码是什么将完全满足您的需求。