好的,你好。我正在尝试比较两个坐标类型(x、y、z)的对象,并且我的代码编译没有错误,但输出并不完全正确。在我看来,我的输入没有被保存,但我不知道为什么。我只包括了相关的定义。
头文件:
#ifndef COORDINATE_H //if not defined
#define COORDINATE_H //Define
#include <iostream>
using namespace std;
class Coordinate
{
friend istream& operator>>(istream &, Coordinate &);
friend ostream& operator<<(ostream &, const Coordinate &);
public:
Coordinate(double = 0.0, double = 0.0, double = 0.0); //my default constructor
Coordinate operator+(const Coordinate &);
Coordinate operator-(const Coordinate &);
Coordinate operator*(const Coordinate &);
Coordinate& operator=(const Coordinate &);
bool operator==(const Coordinate &);
bool operator!=(const Coordinate &);
void setCoordinate(double a, double b, double c);
private:
double x;
double y;
double z;
};
#endif //end definition.
定义:
#include <iomanip>
#include "Coordinate.h" //including the Coordinate header file
using namespace std;
bool Coordinate::operator==(const Coordinate & d)
{
return (this->x == d.x && this->y == d.y && this->z == d.z);
}
bool Coordinate::operator!=(const Coordinate & d)
{
return !(this->x == d.x && this->y == d.y && this->z == d.z);
}
Coordinate& Coordinate::operator=(const Coordinate & d)
{
if(this != &d)
{
x = d.x;
y = d.y;
z = d.z;
}
return *this;
}
ostream &operator<<(ostream & out, const Coordinate & d)
{
out << "(" <<d.x << "," << d.y << "," << d.z << ")" << endl;
return out;
}
istream &operator>>(istream & in, Coordinate & g)
{
in >> g.x >> g.y >> g.z;
return in;
}