重载提取和插入运算符pt2C++
Overloading Extraction and Insertion Operators pt2 C++
这是我之前发布的问题的pt2在我编辑后,它是否会得到回答我想已经考虑过了。
好的,所以我现在尝试输出一个+bi:
std::ostream& operator<< (std::ostream& out, complex const& c) {
return out << c.getReal() << "+" << c.getImag() << "i";
}
用于输入:
std::istream& operator>> (std::istream& in, complex& c) {
double h, j;
if (in >> h >> "+" >> j >> "i") {
c.set(h, j);
}
return in;
}
然而,当我编译时,我得到了以下错误:
这是我的complex.cpp文件(类复杂实现文件)的第181行,上面函数定义的if (in >> h >> "+" >> j >> "i") {
所在:
binary '>>': no operator found which takes a right-hand operand of type 'const char [2]' (or there is no acceptable conversion)
以下是我的complex.h文件中friend std::istream &operator>> (std::istream &in, complex& c);
原型所在的第45行的全部内容(请注意,每一个错误都是单独的,这一行总共有7个错误)。
'istream':is not a member of 'std'
syntax error missing ';' before '&'
'istream':'friend' not permitted on data declarations
missing type specifier-int assumed. Note:C++ does not support default-int
unexpected token(s) preceding';'
namespace "std" has no member "istream"
namespace "std" has no member "istream"
以下是我的complex.h文件的第46行,其中
friend std::ostream &operator<<(std::ostream &out, complex c);
位于
'ostream': is not a member of 'std'
syntax error: missing ';' before '&'
'ostream':'friend' not permitted on data declarations
missing type specifier -int assumed.Note: C++ does not support default-int
unexpected token(s) preceding ';'
namespace "std" has no member "ostream"
namespace "std" has no member "ostream"
我注意到两者都是相同类型的错误。注意:我有
#include<iostream>
using namespace std;
complex.cpp文件和main.cpp文件
您正试图在中输入只读字符串文字
if (in >> h >> "+" >> j >> "i")
这是行不通的。您需要做的是创建一个变量来存储输入的文本内容。由于内容不需要,我们可以在完成后将其扔掉。这将给你一些类似的东西
std::istream& operator>> (std::istream& in, complex& c) {
double h, j;
char eater;
if (in >> h >> eater >> j >> eater) { // eater now consumes the + and i
c.set(h, j);
}
return in;
}
至于头文件中的错误,您需要在头文件中包含#include <iostream>
,以便编译器知道istream
和ostream
是什么。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 重载提取和插入运算符pt2C++