对于Array类,含义即建立某个数组,数组类型为T,T可以是任何类,比如之前的Point类(某点的x,y坐标)。
通透的瞬间:Arrayofpoints类的本质:建立一个数组,数组类型为某点的一对坐标(x,y)
*points是对象的数据成员,指向Point类的指针;
构造函数:为points赋予地址,地址的大小为size;
析构函数:删除points的地址
复制构造函数:某对象v,其含有points指针指向的地址和值,以及size大小。首先获取对象v的数据成员size,然后为数据成员points用new分配地址建立数组,数组类型为Point(Point含有数据成员x和y,即某点的的坐标),接着使其地址的值与v相等。相当于通过指针指向的地址为数组赋值。
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <cassert>
using namespace std;
class Point{
private:
int x, y;
public:
static int count;
Point() :x(0), y(0){
count++;
cout << "default Point constructed" << endl;
}
Point(int x, int y) :x(x), y(y){
count++;
cout << "Point constructed" << endl;
}
~Point(){
count--;
cout << "Point deconstructed" << endl;
}
int getx() const{
return x;
}
int gety() const{
return y;
}
void move(int newx, int newy){
x = newx;
y = newy;
}
};
class Arrayofpoints{
private:
Point *points;
int size;
public:
Arrayofpoints(int size) :size(size){
points = new Point[size]; //two* "default Point constructed"
cout << "Arrayofpoints constructed" << endl;
}
~Arrayofpoints(){
cout << "deleting..." << endl;
delete[] points;
}
Arrayofpoints(const Arrayofpoints &v){
size = v.size;
points = new Point[size]; //two* "default Point constructed"
for (int i = 0; i < size; i++){
points[i] = v.points[i];
}
cout << "Arrayofpoints copier called" << endl;
}
Point &element(int index){
assert(index >= 0 && index < size);
return points[index];
}
};