Point& element(int index)这是什么函数为什么还有&?
points.element(0).move(5, 0);这是啥为什么points还能调用element?
// 6-18动态数组类.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cassert>
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;
};
//动态数组类
class ArrayofPoints {
public:
ArrayofPoints(int size) :size(size) {
points = new Point[size];
}
~ArrayofPoints() {
cout << "Deleting..." << endl;
delete[]points;
}
//获得下标为index的的元素
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;
}