对象指针
对象指针定义形式
类名 *对象指针名;
例: Point a(5,10);
Piont *ptr;
ptr=&a;
通过指针访问对象成员(等同于对象名访问对象成员)
对象指针名->成员名
例:ptr->getx() 相当于 (*ptr).getx();
动态创建对象数组
//一维
#include <iostream>
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<< "Constructor called."<<endl;
}
~Point() { cout<<"Destructor called."<<endl; }
int getX() const { return x; }
int getY() const { return y; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
private:
int x, y;
};
int main(){
Point *ptr = new Point[2];//创建对象数组
ptr[0].move(5,10);//通过指针访问数组元素的成员
ptr[1].move(15,20);
cout << "Deleting..." << endl;
delete[] ptr;//删除整个对象数组
return 0;
}
动态创建多维数组
char (*fp)[3];
fp = new char[2][3];
#include <iostream>
using namespace std;
int main() {
int (*cp)[9][8] = new int[7][9][8];
for (int i = 0; i < 7; i++)
for (int j = 0; j < 9; j++)
for (int k = 0; k < 8; k++)
*(*(*(cp + i) + j) + k) =(i * 100 + j * 10 + k);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 9; j++) {
for (int k = 0; k < 8; k++)
cout << cp[i][j][k] << " ";
cout << endl;
}
cout << endl;
}
delete[] cp;
return 0;
}
将动态数组封装成类
-
更加简洁,便于管理
- 可以在访问数组元素前检查下标是否越界
例 6-18 动态数组类
#include <iostream>
#include <cassert>
using namespace std;
class Point { //类的声明同例6-16 … };
class ArrayOfPoints { //动态数组类
public:
ArrayOfPoints(int size) : size(size) {
points = new Point[size];
}
~ArrayOfPoints() {
cout << "Deleting..." << endl;
delete[] points;
}
Point& element(int index) {
assert(index >= 0 && index < size);
return points[index];
}
private:
Point *points; //指向动态数组首地址
int size; //数组大小
};
int main() {
int count;
cout << "Please enter the count of points: ";
cin >> count;
ArrayOfPoints points(count); //创建数组对象
points.element(0).move(5, 0); //访问数组元素的成员
points.element(1).move(15, 20); //访问数组元素的成员
return 0;
}