//classfile.h
//Pclassfile.h
#include <iostream>
using namespace std;
class Point {
public:
Point() ;
Point(int x, int y);
~Point() ;
int getX()const;
int getY()const;
void move(int newX, int newY);
private:
int x, y;
};
class ArrayOfPoints {
public:
ArrayOfPoints(int size); //构造函数
~ArrayOfPoints(); //析构函数
Point& element(int index); //获得下表为index的数组元素
private:
Point* points; //指向动态数组首地址
int size;
};
//classfile.cpp
//Pclassfile.cpp
#include <iostream>
#include <cassert>
#include "classfile.h"
using namespace std;
Point::Point() :x(0), y(0) {
cout << "default constructor called" << endl;
}
Point::Point(int x, int y) :x(x), y(y) {
cout << "constructor called" << endl;
}
Point::~Point(){
cout << "destructor called" << endl;
}
int Point::getX()const
{
return x;
}
int Point::getY()const
{
return y;
}
void Point::move(int newX, int newY)
{
x = newX;
y = newY;
}
ArrayOfPoints::ArrayOfPoints(int size) :size(size)
{
points = new Point[size];
}
ArrayOfPoints::~ArrayOfPoints()
{
cout << "deleting..." << endl;
delete[]points;
}
Point& ArrayOfPoints::element(int index)
{
assert(index >= 0 && index < size); //如果下标越界,程序终止
return points[index];
}
//main.cpp
/*1.编译运行例6-21(对象的浅复制),
看看程序是否真的出错,
原因是什么?修改该程序,使其正确。*/
#include <iostream>
#include <cassert>
#include "classfile.h"
using namespace std;
int main()
{
int count;
cout << "please enter the count of points:" << endl;
cin >> count;
ArrayOfPoints pointsArray1(count); //创建对象数组
pointsArray1.element(0).move(5, 10);
pointsArray1.element(1).move(15, 20);
ArrayOfPoints pointArray2 = pointsArray1;
cout << "copy of pointArray1:" << endl;
cout << "Point_0 of array2:" << pointArray2.element(0).getX() << ","
<< pointArray2.element(0).getY() << endl;
cout << "Point_1 of array2:" << pointArray2.element(1).getX() << ","
<< pointArray2.element(1).getY() << endl;
pointsArray1.element(0).move(25, 30);
pointsArray1.element(1).move(35, 40);
cout << "After the moving of pointArray1:" << endl;
cout << "Point_0 of array2:" << pointArray2.element(0).getX() << ","
<< pointArray2.element(0).getY() << endl;
cout << "Point_1 of array2:" << pointArray2.element(1).getX() << ","
<< pointArray2.element(1).getY() << endl;
return 0;
}