重载提取和插入运算符pt2C++

Overloading Extraction and Insertion Operators pt2 C++

本文关键字:运算符 pt2C++ 插入 提取 重载      更新时间:2023-10-16

这是我之前发布的问题的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>,以便编译器知道istreamostream是什么。