Use "new" and "delete": File: AllocNewTest.cpp
-
#include <iostream><br /><br />class CCC<br />{<br />public:<br /> CCC(){};<br /> CCC(int);<br /> CCC(int, double);<br /> int ii;<br /> double dd;<br />};<br /><br />CCC::CCC(int _ii)<br /> : ii(_ii)<br />{<br />};<br /><br />CCC::CCC(int _ii, double _dd)<br /> : ii(_ii), dd(_dd)<br />{<br />};<br /> <br />using namespace std;<br /><br />main()<br />{<br /> CCC *cc1 = new CCC(4, 5.5); // Pointer. Contructor called.<br /> CCC *cc2 = new CCC[5]; // Pointer to an array of objects.<br /> CCC &cc3 = *new CCC; // Reference<br /><br /> cc1->ii=5;<br /> cc2[3].ii=6;<br /> cc3.ii=7;<br /><br /> cout << cc1->ii << endl;<br /> cout << cc2[3].ii << endl;<br /> cout << cc3.ii << endl;<br /><br /> delete cc1;<br /> delete [] cc2;<br /> delete & cc3;<br />}<br />
Note the difference between:- new CCC(3) creates memory for a single object who's integer member is set to 3.
- new CCC[3] creates memory for three objects of type CCC and no variables are set.
Compile: g++ -o AllocNewTest AllocNewTest.cpp
沒有留言:
張貼留言