我正在尝试为一个非常简单的 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,其中数组的每个元素都是它自己的对象。
我得到的代码的行为在评论中描述。