Я пытаюсь перегрузить операторы < < (cout) и >> (cin) на некоторое время для класса сложных чисел, которому мне дали прототипы в a. h файл.перегрузка Извлечение и вставка << >> operator C++
Это моя попытка сделать это в файле class.cpp:
std::istream &operator>> (std::istream &in, complex& c) {
double h, j;
in >> h >> j;
c.set(h,j);
return in;
}
std::ostream &operator<<(std::ostream &out, complex c) {
out << c.getReal;
out << c.getImag;
return out;
}
Это действительно первый раз, когда я видел
std:: istream
иstd:: ostream
, а не соиЬ и CIN и я» м на самом деле не знаю, какcout <<
иcin >>
все связаныЯ Протестируйте его на файл main.cpp, но я получаю ошибки
>>
должен поглотить сложный аргумент в комплекс класса аргумента и изменить значение частных членовreal
иimag
Не уверен, если я должен использовать свой набор функций здесь
Это является файлом протипа .h, заполненным мной:
#ifndef COMPLEX_H
#define COMPLEX_H
class complex {
public:
complex();
complex(double a);
complex(double a, double b);
complex(int a, int b);
void print() const;
void set(double a = 0, double b = 0);
void set(int a = 0, int b = 0);
double getReal() const;
double getImag() const;
void get(double&, double&) const;
complex operator+ (double& x);
complex operator+ (complex&);
complex operator+= (complex&);
complex operator+= (int&);
complex operator++ (int);
complex operator++();
complex operator- (double&);
complex operator- (complex&);
complex operator-= (complex&);
complex operator-= (double&);
complex operator-- (int);
complex operator--();
complex operator* (complex&);
complex operator* (double&);
complex operator*= (complex&);
complex operator*= (double&);
complex operator/ (complex&);
complex operator/= (complex&);
complex operator/= (double);
complex operator/ (double);
void operator= (const complex&);
bool operator== (complex&);
bool operator!=(complex &c);
friend std::istream &operator>> (std::istream &in, complex& c);
friend std::ostream &operator<<(std::ostream &out, complex c);
/*complex conj() const;
double norm() const;
double modulus() const;
*/
private:
double real;
double imag;
};
#endif // COMPLEX_H
Может ли кто-нибудь показать мне, как правильно перегрузить это?
Ok, так что я сейчас пытаюсь для вывода а + би:
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;
}
Однако я получаю следующее сообщение об ошибке при компиляции:
Этот для строки 181 моего файла complex.cpp (файл сложной реализации класса), где находится 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)
для всей линии 45 (примечание: каждая ошибка является отдельной, всего 7 для этой строки) моего файла complex.h, где находится friend std::istream &operator>> (std::istream &in, complex& c);
protoype.
'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"
являются следующие для линии 46 моего файла complex.h где
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
Кажется разумным, за исключением того, что вам нужно вызвать функции 'get', а не просто назвать их. Измените 'getReal' на' getReal() 'и аналогично' getImag' на 'getImag()' в 'operator <<'. Кроме того, вы подумали о разделении выходных частей? Скажем, с запятой. Кроме этого, вам может быть лучше просить об этом на [CodeReview.SE] (http://codereview.stackexchange.com/) – BoBTFish
Каким образом код не работает? ... и я скажу @BoBTFish, утверждая, что это разумно, несмотря на то, что функция ввода не проверяет свои входы перед использованием! –
Вам необходимо выполнить свои функции ['const' correct] (https://isocpp.org/wiki/faq/const-correctness). – Simple