出自:C++语言程序设计基础——清华大学郑莉老师
#include "pch.h"
#include <iostream>
#include<cassert>
using namespace std;
class Point {
private:
int x, y;
public:
Point() :x(0), y(0) {
cout << "调用默认构造函数..." << endl;
}
Point(int x, int y) :x(x), y(y) {
cout << "调用构造函数..." << endl;
}
~Point() {
cout << "调用析构函数..." << endl;
}
int getX() const { return x; }
int getY() const { return y; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
};
class ArrayOfPoint {
private:
Point *p;
int size;
public:
ArrayOfPoint(int size) :size(size) {
p = new Point[size];
cout << "正在调用构造函数..." << endl;
}
~ArrayOfPoint() {
cout << "deleting..." << endl;
cout << "正在调用析构函数..." << endl;
delete[] p;
}
Point& element(int index) {
cout << "此时调用..." << endl;
assert(index >= 0 && index < size);
return p[index];
}
};
int main()
{
int size;
cout << "Input the size of points: ";
cin >> size;
ArrayOfPoint p(size);
p.element(0).move(5, 0);
p.element(1).move(15, 20);
return 0;
}
注意:
代码中element函数返回对象的引用,原因如下:
返回“引用”可以用来操作数组对象内部的数组元素。如果返回“值”,则不能修改对象内部的数组元素的值。
assert(index >= 0 && index < size); 可以在访问数组元素之前检查数组下标是否越界。