首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重载提取和插入操作符pt2 C++

重载提取和插入操作符pt2 C++
EN

Stack Overflow用户
提问于 2015-12-12 00:07:54
回答 1查看 79关注 0票数 0

这是我之前发布的问题的pt2,如果它在我编辑后是否会被回答,我想,因为它已经被认为是“回答”了。

好的,现在我正在尝试输出a+ bi:

代码语言:javascript
复制
std::ostream& operator<< (std::ostream& out, complex const& c) {
    return out << c.getReal() << "+" << c.getImag() << "i";
}

并供投入:

代码语言:javascript
复制
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") {位于上述函数定义的位置:

代码语言:javascript
复制
binary '>>': no operator found which takes a right-hand operand of type 'const char [2]' (or there is no acceptable conversion) 

下面是friend std::istream &operator>> (std::istream &in, complex& c);原型所在的comp.h文件的第45行(每个错误都是单独的,共7行)的所有内容。

代码语言:javascript
复制
'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"

下面是我的comp.h文件的第46行,其中

代码语言:javascript
复制
friend std::ostream &operator<<(std::ostream &out, complex c);

找出

代码语言:javascript
复制
'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"

我注意到两者都是相同类型的错误。注:我有

代码语言:javascript
复制
#include<iostream>

using namespace std;

complex.cpp文件和main.cpp文件

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-12 00:17:59

您正在尝试在只读字符串中输入

代码语言:javascript
复制
if (in >> h >> "+" >> j >> "i")

这是行不通的。您需要做的是创建一个变量来存储输入的文本内容。因为不需要内容,所以我们可以在做完后把它扔掉。这会给你一些线索

代码语言:javascript
复制
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>,以便编译器知道istreamostream是什么。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34234591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档