3

好的,你好。我正在尝试比较两个坐标类型(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;
    }
4

1 回答 1

3

如果您希望以与您编写的相同格式阅读,则需要明确说明。

可以使用标准 C++ 流来实现:

istream& operator>>(istream& in, Coordinate& g) {
    char c;
    in >> c;        if (c != '(') { ... }
    in >> g.x >> c; if (c != ',') { ... }
    in >> g.y >> c; if (c != ',') { ... }
    in >> g.z >> c; if (c != ')') { ... }
    return in;
}

不幸的是,这种解决方案不能正确回溯或任何无效输入。当然,您可以设置失败位并继续。要自动检查文字,您可以添加重载 foristream&并使用std::ws来显式丢弃空格:

istream& operator>>(istream& in, char c) {
    in >> ws;
    if (in.peek() == c)
        in.ignore();
    else
        in.clear(ios::failbit);
    return in;
}

istream& operator>>(istream& in, Coordinate& g) {
    return in >> '(' >> g.x >> ',' >> g.y >> ',' >> g.z >> ')';
}

如果你需要比这更多的东西,我想它会很快变得笨拙。您基本上最终会逐个字符地手动解析输入。此时,您应该只使用适当的解析库来省去麻烦。

于 2012-04-25T00:33:20.957 回答