#include <iostream>
using namespace std;
class Point {
private:
int x;
int y;
static int numCreatedObjects;
public:
Point() : x(0), y(0) {
numCreatedObjects++;
}
Point(int _x, int _y) : x(_x), y(_y) {}
~Point() {
cout << "Destructed..." << endl;
}
void setXY(int _x, int _y) {
this->x = _x;
this->y = _y;
}
到目前为止似乎编译得很好。检查构造函数和析构函数,直到它们完全可操作。
int getX() const { return x; }
int getY() const { return y; }
// *this + pt2 ->
Point operator+(Point& pt2) {
Point result(this->x + pt2.getX(), this->y + pt2.getY());
return result;
}
//operator overloading
Point& operator=(Point& pt) {
this->x = pt.x;
this->y = pt.y;
return *this;
}
static int getNumCreatedObject() {
return numCreatedObjects; }
friend void print(const Point& pt);
friend ostream& operator<<(ostream& cout, Point& pt);
friend class SpyPoint;
};
SpyPoint 类上的 hack_all_info 函数必须这样做 将 Point pt x, y 更改为 40, 60. 并且 static int 必须更改为 10.
所以我这样编译;
//static (numCreatedObjects)
int Point::numCreatedObjects = 0;
void print(const Point& pt) {
cout << pt.x << ", " << pt.y << endl;
}
ostream& operator<<(ostream& cout, Point& pt) {
cout << pt.x << ", " << pt.y << endl;
return cout;
}
class SpyPoint {
public:
void hack_all_info(Point &pt) {
pt.x = 40;
pt.y = 60;
cout << "Hacked by SpyPoint" << endl << "x:" << pt.x << endl << "y: " << pt.y << endl;
cout << "numCreatedObj.: " << pt.numCreatedObjects << endl;
}
};
int main() {
Point pt1(1, 2);
cout << "pt1 : ";
print(pt1);
cout << endl;
Point* pPt1 = &pt1;
cout << "pt1 : ";
cout << pPt1->getX() <<", "<< pPt1->getY() << endl;
cout << "pt1 : ";
Point* pPt2 = new Point(10, 20);
cout << endl;
cout << "pt2 : ";
cout << pPt2->getX() << ", " << pPt2->getY() << endl;
cout << endl;
delete pPt1;
delete pPt2;
cout << "pt1 NumCreatedObject : ";
cout << Point::getNumCreatedObject() << endl;
Point pt2(10, 20);
Point pt3(30, 40);
Point pt4 = pt2 + pt3;
cout << "pt1 NumCreatedObject : ";
cout << Point::getNumCreatedObject() << endl << endl;
// object array
Point* ptAry = new Point[5];
cout << "pt2 NumCreatedObject : ";
cout << Point::getNumCreatedObject() << endl;
cout << endl;
delete[] ptAry;
cout << endl;
// friend class
SpyPoint spy;
cout << "pt1 info" << endl;
spy.hack_all_info(pt1);
cout << "pt4 info" << endl;
spy.hack_all_info(pt4);
return 0;
}
从这里编译没有问题,但是执行时出错
但是我不知道指针错在哪里:(