C++对象数组的创建
C++对象数组的创建
使用一维指针创建对象数组:
- #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;
- }
结果:
[cpp]
- >>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
|
评论暂时关闭