友情和重载运算符>>

Friending cin and overloading operator >>

本文关键字:gt 运算符 重载 友情      更新时间:2023-10-16

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

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

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

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