友情和重载运算符>>
Friending cin and overloading operator >>
好的,你好。我正在尝试比较坐标类型(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 >> ')';
}
如果你需要比这更复杂的东西,我想它会很快变得笨拙。您基本上最终会逐个字符手动解析输入。此时,您应该使用适当的解析库来省去麻烦。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 是否需要使用 - &gt;运算符在C 中调用成员函数时