C ++运算符>>重载问题:仅更改对象一次

时间:2018-12-16 12:40:16

标签: c++ stream operator-overloading constructor-overloading

我具有以下Vector3D代码,由于某种原因,cin只能更改一次对象值。你知道为什么吗? 我想这与“ const”定义有关,但我不确定。 同时添加代码(部分)和测试

// code:
class Vector3D
{
private:
    double _x, _y, _z;
public:
    Vector3D() : _x(0), _y(0), _z(0) {};
    Vector3D(double x, double y, double z) : _x(x), _y(y), _z(z) {};
    Vector3D(const double parm[DIMENSION]) : _x(parm[0]), _y(parm[1]), 
             _z(parm[2]) {};

    const Vector3D operator+(const Vector3D &other) const; 
    Vector3D &operator+=(const Vector3D &other);
    const double &operator[](int idx) const;
    double &operator[](int idx);
    friend ostream &operator<<(ostream &out, const Vector3D &c);
    friend istream &operator>>(istream &in, Vector3D &c);
};

const Vector3D Vector3D::operator+(const Vector3D &other) const {
    return Vector3D(*this) += other; 
}

Vector3D &Vector3D::operator+=(const Vector3D &other) {
    (*this)._x += other._x;
    (*this)._y += other._y;
    (*this)._z += other._z;
    return *this; 
}

const double &Vector3D::operator[](int idx) const {
    assert(idx >= 0 && idx < DIMENSION);
    switch (idx)
    {
        case 0:
            return _x;
        case 1:
            return _y;
        case 2:
            return _z;
        default:
            return _x; // not reachable
    }
}

double &Vector3D::operator[](int idx)
{
    assert(idx >= 0 && idx < DIMENSION);
    switch (idx)
    {
        case 0:
            return _x;
        case 1:
            return _y;
        case 2:
            return _z;
        default:
            return _x; // not reachable
    }
}

ostream &operator<<(ostream &out, const Vector3D &c)
{
    out << c._x << " " << c._y << " " << c._z;
    return out;
}

istream &operator>>(istream &in, Vector3D &c)
{
    in >> c._x >> c._y >> c._z;
    return in;
}



// test: 
void readFromStreamTest(int &tests) {
    std::stringstream os;
    os << 8.0 << " " << 3.0 << " " << 4.0;
    Vector3D a;
    os >> a;
    os << a; // "8 3 4"  as should be
    os.str(std::string());
    os << 2.1 << " " << 3.1 << " " << 4.1;
    os >> a;
    os.str(std::string());
    os << a;
    if (os.str()!=("2.1 3.1 4.1"))
    {
        std::cerr << "failed. should be 2.1 3.1 4.1 but was " << a;
    }
}

测试结果:“失败。应该是2.1 3.1 4.1,但是是8 3 4”(旧值!)

1 个答案:

答案 0 :(得分:2)

您不能像这样使用 stringstream ,在提取包含抛出os >>之后,您将无法再通过os.str(value)os <<对其进行修改,如果您不这样做的话例如在

之前致电os.clear()
void readFromStreamTest(int &tests) {
  std::stringstream os;
  os << 8.0 << " " << 3.0 << " " << 4.0;
  Vector3D a;
  os >> a;
  os.clear();
  os << a; // "8 3 4"  as should be
  os.str(std::string());
  os << 2.1 << " " << 3.1 << " " << 4.1;
  os >> a;
  os.str(std::string());
  os.clear();
  os << a;
  if (os.str()!=("2.1 3.1 4.1"))
  {
    std::cerr << "failed. should be 2.1 3.1 4.1 but was " << a;
  }
}

P.S。我修改了您的原始代码以使其可编译