使用一維指針創建對象數組:
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : [email protected]
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
int nextStudentID = 1;
class StudentID
{
public:
StudentID()
{
cout << "StudentID()" << endl;
value = nextStudentID++;
cout << "value:" << value << endl;
}
~StudentID()
{
--nextStudentID;
cout << "~StudentID()" << endl;
}
protected:
int value;
};
class Student
{
public:
Student(string pName = "noName")
{
cout << "Student()" << endl;
name = pName;
cout << "name:" << name << endl;
}
~Student()
{
cout << "~Student()" << endl;
}
protected:
string name;
StudentID id;
};
int main(int argc, char **argv)
{
int i;
cin >> i;
Student *p = new Student [i];
delete[] p;
cout << "nextStudentID:" << nextStudentID << endl;
return 0;
}
結果:
>>3
StudentID()
value:1
Student()
name:noName
StudentID()
value:2
Student()
name:noName
StudentID()
value:3
Student()
name:noName
~Student()
~StudentID()
~Student()
~StudentID()
~Student()
~StudentID()
nextStudentID:1
使用二維指針創建動態數組:
//============================================================================
// Name : main.cpp
// Author : ShiGuang
// Version :
// Copyright : [email protected]
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string>
using namespace std;
int nextStudentID = 1;
class StudentID
{
public:
StudentID()
{
cout << "StudentID()" << endl;
value = nextStudentID++;
cout << "value:" << value << endl;
}
~StudentID()
{
--nextStudentID;
cout << "~StudentID()" << endl;
}
protected:
int value;
};
class Student
{
public:
Student(string pName = "noName")
{
cout << "Student()" << endl;
name = pName;
cout << "name:" << name << endl;
}
~Student()
{
cout << "~Student()" << endl;
}
protected:
string name;
StudentID id;
};
int main(int argc, char **argv)
{
int i, j;
string temp;
cin >> i;
Student **p = new Student *[i];
for (j = 0; j < i; j++)
{
cout << "j:" << j << endl;
cin >> temp;
p[j] = new Student(temp);
cout << "nextStudentID:" << nextStudentID << endl;
}
for (j = i - 1; j >= 0; j--)
delete p[j];
// delete[] p; // 這句話好像沒作用
cout << "nextStudentID:" << nextStudentID << endl;
return 0;
}
結果:
>>3
j:0
>>shiguang1
StudentID()
value:1
Student()
name:shiguang1
nextStudentID:2
j:1
>>shiguang2
StudentID()
value:2
Student()
name:shiguang2
nextStudentID:3
j:2
>>shiguang3
StudentID()
value:3
Student()
name:shiguang3
nextStudentID:4
~Student()
~StudentID()
~Student()
~StudentID()
~Student()
~StudentID()
nextStudentID:1
兩者的區別:
一維指針在建立指針的時候,申請並創建了三個對象。
二維指針在建立指針的時候,只創建了一個指針數組(即3*4Byte),數組裡面的元素用來存放三個對象的地址,各個對象地址在後面由new創建獲得。所以對應的delete函數應該是delete p[j];而不是delete[] p。
摘自 sg131971的學習筆記