3

こんにちは、こんにちは。座標タイプ(x、y、z)の2つのオブジェクトを比較しようとしていますが、コードはエラーなしでコンパイルされますが、出力は完全に正しくありません。私には、入力が保存されていないように見えますが、その理由がわかりません。私は関連する定義だけを含めました。

ヘッダーファイル:

#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;
}

残念ながら、この種の解決策は、無効な入力に対して正しくバックトラックまたは何かを行いません。もちろん、失敗ビットを設定して先に進むこともできます。リテラルを自動的にチェックするには、オーバーロードを追加して、空白を明示的に破棄するためistream&に使用できます。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 >> ')';
}

これ以上複雑なものが必要な場合は、すぐに扱いにくくなると思います。基本的に、入力を1文字ずつ手動で解析することになります。その時点で、問題を回避するために適切な解析ライブラリを使用する必要があります。

于 2012-04-25T00:33:20.957 に答える