朋友cin和重载运算符>>

时间:2012-04-24 19:22:11

标签: c++

好的,你好。我试图比较坐标类型(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.

Defintions:

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

1 个答案:

答案 0 :(得分:2)

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

可以使用标准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 >> ')';
}

如果你需要比这更多的东西,我想它会很快变得笨拙。您基本上会逐个手动解析输入。那时你应该使用一个合适的解析库来避免麻烦。