用C++设计类来模拟将军回家的场景.(类似于将军饮马问题)
已经将类编写完了,实在是不清楚main函数中怎么能实现对家和人的对象实例化,编写的时候老是报错,帮帮我,如何在main函数中实例化对象,然后再用单目重载运算符来实现求两点之间的距离,以及用双目重载运算符求人的坐标取反之后的距离。代码如下,可以帮我将他完善完了吗,谢谢大家!
#include <iostream>
#include <math.h>
using namespace std;
// 类的设计, 模拟场景 将军回家
class Home;
class CPoint;
class Rule;
class Person;
class IMap;
class IMap {//地理接口,只提供接口规则,不提供实现(继承是让子代继承父代的所有东西)
public:
virtual double getDis5(IMap& oth)=0; //纯虚函数
virtual CPoint getP()=0;
};
class CPoint {
private:
int x = 0;
int y = 0;
public:
CPoint(int x = 2, int y = 2) {
this->x = x;
this->y = y;
}
int getX() const { return this->x; }
void setX(int x) { this->x = x % 100; }
int getY() const { return this->y; }
void setY(int x) { this->y = y % 100; }
CPoint* operator-() {
//this->x = -this->x;
this->y = -this->y;
return this;
}
friend double operator-(CPoint&p1,CPoint&p2) {
return sqrt((p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) +(p1.getY() - p2.getY()) * (p1.getY() - p2.getY()));
}
};
class Home : public IMap {
private:
string name;
CPoint address;
public:
Home (const char *name,int x=2,int y=2):address(x,y) {}
CPoint setaddress(int x,int y){
this->address = x;
this->address = y;
return address;
}
CPoint getP() { return this->address; }
double getDis5(IMap& oth) {
return sqrt((address.getX() -oth.getP().getX() ) * (address.getX() - oth.getP().getX()) +(address.getY() - oth.getP().getY()) * (address.getY()- oth.getP().getY()));
}
};
class Person : public IMap {
private:
string name;
CPoint loc;
static Person* m_instance;
private:
Person(){}
Person(const Person& oth) {}
Person operator=(const Person& oth);
public:
static Person* getInstance() {
Person* temp;
if (m_instance == NULL) {
m_instance = temp = new Person();
}
else {
temp = m_instance;
}
return temp;
}//确定人只有一个
CPoint getP(){ return this->loc;}
Person(const char *name,int x=2,int y=2):loc(x,y) {}
CPoint setloc(int x,int y){
this->loc = x;
this->loc = y;
return loc;
}
double getDis5(IMap& oth) {
return sqrt((loc.getX()-oth.getP().getX() ) * (loc.getX()- oth.getP().getX()) +(loc.getY() - oth.getP().getY()) * (loc.getY()- oth.getP().getY()));
}
};
Person* Person::m_instance = NULL;
//工具类,直接调用即可
class Rule {
public:
static double getDis3(CPoint& p1,CPoint& p2) {
return sqrt((p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) +
(p1.getY() - p2.getY()) * (p1.getY() - p2.getY()));
}
};
int main()
{
Person* p = Person::getInstance();
Person* p1 = Person::getInstance();
if (p == p1) {
cout << "ok" << endl;
}
Home h1("junying");
h1.setaddress(2,5);
cout<<h1.getP()<<endl;
Person pp1("jiangjun");
//cout << p.loc - h->getAddress << endl; // 重载双目 -
//cout << p.loc - (-(h->getAddress)) << endl; // 重载单目 -
return 0;
}
去主页搜索一下,应该可以查到
目测,你没有为 CPoint 重载 << 输出