Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Другие темы раздела
C++ Получить строку, состоящую из пяти звездочек Получить строку, состоящую из пяти звездочек (символов "*"). Нужно вывести не символы, а именно строку. Помогите пожалуйста, очень нужно! https://www.cyberforum.ru/ cpp-beginners/ thread704206.html Функция дужки(приоритет операций) в калькуляторе C++
Надо сделать скобки в калькуляторе: сделать дополнительную ф-цию которая будет считать введеные даные после ввода "(", после ввода ")" возвращает результат в главную функцию(ну вместо ). Ну глянув на...
C++ Проверка ошыбок https://www.cyberforum.ru/ cpp-beginners/ thread704177.html
Есть код програмы но гдето есть ошыбка немогу с виду найти мне сказали запустить дебагер или както так и там будет видно как изменяютса переменные . скажите как запустить на с++.
C++ Найти тройки чисел https://www.cyberforum.ru/ cpp-beginners/ thread704157.html
Найти все такие тройки натуральных чисел x, y, z из интервала от 1 до 20, для которых выполняется равенство: x*y2=z2 Огромное спасибо заранее.
Разобрать GIF файл по пикселям и вывести в матрицу C++
Требуется разобрать GIF файл по пикселям и вывести на матрицу. У кого нибудь есть опыт работы с GIF файлами на уровне программы. Поделитесь инфой или примерами кода если не жалко :) Заранее спасибо
C++ Дана прямоугольная матрица действительных чисел Дана прямоугольная матрица действительных чисел. Найти количество строк, среднее арефметическое элементов которых меньше заданной величины. https://www.cyberforum.ru/ cpp-beginners/ thread704138.html
C++ Дана прямоугольная матрица действительных чисел https://www.cyberforum.ru/ cpp-beginners/ thread704127.html
Дана прямоугольная матрица действительных чисел. Найти количество строк, среднее арефметическое элементов которых меньше заданной величины.
C++ Одномерный массив
1.Найти кол-во элементов массива,больших С. 2.Найти произведение элементов массива,расположенных после максимального по модулю элемента. 3.Преобразовать массив,чтобы сначала располагались все...
C++ Вывод списка в виде отдельных функций https://www.cyberforum.ru/ cpp-beginners/ thread704117.html
Реализация в коде удаления,поиска,и вставки элементов,программа удаляет тока 1 элемент списка. Помогите исправить пожалуйста. #include "stdafx.h" #include <iostream> using namespace std;...
C++ Конструкция switch - магия какая-то Сел позавчера за изучение плюсов, изучаю по книжке В.В.Подбельского В этой книжке приведён пример использования конструкции switch. Сама суть программы состояла в выведении названий все нечётных... https://www.cyberforum.ru/ cpp-beginners/ thread704094.html
C++ Считать информацию из файла в массив структур
Здравствуйте! Выполняю упражнение из книги Прата "С++ язык" Суть в том, что нужно из файла считать определенное количество элементов (количество указано в самом начале файла), и записать эти...
C++ Помощь с функцией https://www.cyberforum.ru/ cpp-beginners/ thread704019.html
Нужно написать функцию, которая делает возможным приоритет операций для данной программы (т.е. использование скобок). Листинг: #include <iostream> #include <stdlib.h> #include <string.h>...
Diagnost
0

Не работает перегрузка операторов при выводе в cout - C++ - Ответ 3731571

21.11.2012, 12:54. Показов 1531. Ответов 1
Метки (Все метки)

Студворк — интернет-сервис помощи студентам
написал свой класс ComplexNumber. перегрузил для него операторы +, -, *, /, <<.
конструкции вида
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ComplexNumber a(5,10);
ComplexNumber b(7, 12);
    
cout << "a = " << a << endl;
cout << "b = " << b << endl;
    
ComplexNumber sum = a + b;
ComplexNumber difference = a - b;
ComplexNumber multiply = a * b;
ComplexNumber divide = a / b;
        
cout << "a + b = " << sum << endl;
cout << "a - b = " << difference << endl;
cout << "a * b = " << multiply << endl;
cout << "a / b = " << divide << endl;
работают на ура.
а вот такая конструкция упорно не работает:
C++
1
cout << (a + b) << endl;
текст программы:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <string>
#include <cmath>
 
using namespace std;
 
class ComplexNumber {
private:
    double re;
    double im;
public:
    ComplexNumber();
    ComplexNumber(double, double);
    
    double getReal();
    double getImaginary();
    
    const ComplexNumber& operator+(const ComplexNumber&);
    const ComplexNumber& operator-(const ComplexNumber&);
    const ComplexNumber& operator*(const ComplexNumber&);
    const ComplexNumber& operator/(const ComplexNumber&);
    
};
 
ComplexNumber::ComplexNumber() {
    this->re = 0;
    this->im = 0;
}
 
ComplexNumber::ComplexNumber(double re, double im) {
    this->re = re;
    this->im = im;
}
 
double ComplexNumber::getReal() {
    return this->re;
}
 
double ComplexNumber::getImaginary() {
    return this->im;
}
 
/*
 * (a + bi) + (c + di) = (a + c) + (b + d)i
 */
const ComplexNumber& ComplexNumber::operator +(const ComplexNumber& number) {
    return ComplexNumber(this->re + number.re, this->im + number.im);
}
 
/*
 * (a + bi) - (c + di) = (a - c) + (b - d)i
 */
const ComplexNumber& ComplexNumber::operator -(const ComplexNumber& number) {
    return ComplexNumber(this->re - number.re, this->im - number.im);
}
 
/*
 * (a + bi) * (c + di) = (ac - bd) + (bc + ad)i
 */
const ComplexNumber& ComplexNumber::operator *(const ComplexNumber& number) {
    double real = this->re * number.re - this->im * number.im;
    double imaginary = this->im * number.re + this->re * number.im;
    return ComplexNumber(real, imaginary);
}
 
/*
 *  a + bi    | ac + bd |   | bc - ad |
 * -------- = |---------| + |---------|
 *  c + di    |c^2 + d^2|   |c^2 + d^2|
 */
const ComplexNumber& ComplexNumber::operator /(const ComplexNumber& number) {
    double real = (this->re * number.re + this->im * number.im) / (pow(number.re, 2) + pow(number.im, 2));
    double imaginary = (this->im * number.re - this->re * number.im) / (pow(number.re, 2) + pow(number.im, 2));
    return ComplexNumber(real, imaginary);
}
 
ostream& operator <<(ostream& out, ComplexNumber* number) {
    out << "FUCK";
    return out;
}
ostream& operator <<(ostream& out, ComplexNumber& number) {
    out.precision(4);
    
    if (number.getReal() == 0 && number.getImaginary() == 0) {
        out << 0;
        return out;
    }
    if (number.getReal() == 0 && number.getImaginary() != 0) {
        out << number.getImaginary() << "i";
        return out;
    }
    if (number.getReal() != 0 && number.getImaginary() == 0) {
        out << number.getReal();
        return out;
    }
    if (number.getReal() != 0 && number.getImaginary() != 0) {
        out << number.getReal();
        if (number.getImaginary() > 0) {
            out << " + " << number.getImaginary();
        } else {
            out << " - " << abs(number.getImaginary());
        }
        out << "i";
        return out;
    }
    return out;
}
 
int main(int argc, char** argv) {
    ComplexNumber a(5,10);
    ComplexNumber b(7, 12);
    
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
        
    ComplexNumber sum = a + b;
    ComplexNumber difference = a - b;
    ComplexNumber multiply = a * b;
    ComplexNumber divide = a / b;
        
    cout << "a + b = " << sum << endl;
    cout << "a - b = " << difference << endl;
    cout << "a * b = " << multiply << endl;
    cout << "a / b = " << divide << endl;
    
    cout << (a + b) << endl;
    return 0;
}
полотенце ошибок:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:126:16: error: no match for ‘operator<<’ in ‘std::cout << a.ComplexNumber::operator+((*(const ComplexNumber*)(& b)))’
main.cpp:126:16: note: candidates are:
/usr/include/c++/4.6/ostream:110:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>::__ostream_type& (*)(std::basic_ostream<_CharT, _Traits>::__ostream_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:110:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘std::basic_ostream<char>::__ostream_type& (*)(std::basic_ostream<char>::__ostream_type&) {aka std::basic_ostream<char>& (*)(std::basic_ostream<char>&)}’
/usr/include/c++/4.6/ostream:119:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>::__ios_type& (*)(std::basic_ostream<_CharT, _Traits>::__ios_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>, std::basic_ostream<_CharT, _Traits>::__ios_type = std::basic_ios<char>]
/usr/include/c++/4.6/ostream:119:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘std::basic_ostream<char>::__ios_type& (*)(std::basic_ostream<char>::__ios_type&) {aka std::basic_ios<char>& (*)(std::basic_ios<char>&)}’
/usr/include/c++/4.6/ostream:129:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:129:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘std::ios_base& (*)(std::ios_base&)’
/usr/include/c++/4.6/ostream:167:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:167:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘long int’
/usr/include/c++/4.6/ostream:171:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:171:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘long unsigned int’
/usr/include/c++/4.6/ostream:175:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:175:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘bool’
/usr/include/c++/4.6/bits/ostream.tcc:93:5: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.6/bits/ostream.tcc:93:5: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘short int’
/usr/include/c++/4.6/ostream:182:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:182:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘short unsigned int’
/usr/include/c++/4.6/bits/ostream.tcc:107:5: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.6/bits/ostream.tcc:107:5: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘int’
/usr/include/c++/4.6/ostream:193:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:193:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘unsigned int’
/usr/include/c++/4.6/ostream:202:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:202:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘long long int’
/usr/include/c++/4.6/ostream:206:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:206:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘long long unsigned int’
/usr/include/c++/4.6/ostream:211:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:211:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘double’
/usr/include/c++/4.6/ostream:215:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:215:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘float’
/usr/include/c++/4.6/ostream:223:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:223:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘long double’
/usr/include/c++/4.6/ostream:227:7: note: std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>]
/usr/include/c++/4.6/ostream:227:7: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘const void*’
/usr/include/c++/4.6/bits/ostream.tcc:121:5: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>::__streambuf_type*) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__streambuf_type = std::basic_streambuf<char>]
/usr/include/c++/4.6/bits/ostream.tcc:121:5: note: no known conversion for argument 1 from ‘const ComplexNumber’ to ‘std::basic_ostream<char>::__streambuf_type* {aka std::basic_streambuf<char>*}’
main.cpp:77:10: note: std::ostream& operator<<(std::ostream&, ComplexNumber*)
main.cpp:77:10: note: no known conversion for argument 2 from ‘const ComplexNumber’ to ‘ComplexNumber*’
main.cpp:81:10: note: std::ostream& operator<<(std::ostream&, ComplexNumber&)
main.cpp:81:10: note: no known conversion for argument 2 from ‘const ComplexNumber’ to ‘ComplexNumber&’
/usr/include/c++/4.6/ostream:528:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const unsigned char*)
/usr/include/c++/4.6/ostream:523:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const signed char*)
/usr/include/c++/4.6/ostream:510:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const char*)
/usr/include/c++/4.6/bits/ostream.tcc:323:5: note: template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const char*)
/usr/include/c++/4.6/ostream:493:5: note: template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const _CharT*)
/usr/include/c++/4.6/ostream:473:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, unsigned char)
/usr/include/c++/4.6/ostream:468:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, signed char)
/usr/include/c++/4.6/ostream:462:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, char)
/usr/include/c++/4.6/ostream:456:5: note: template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, char)
/usr/include/c++/4.6/ostream:451:5: note: template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, _CharT)
/usr/include/c++/4.6/bits/basic_string.h:2693:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::basic_string<_CharT, _Traits, _Alloc>&)
make[2]: *** [build/Debug/GNU-Linux-x86/main.o] Error 1

Вернуться к обсуждению:
Не работает перегрузка операторов при выводе в cout C++
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
21.11.2012, 12:54
Готовые ответы и решения:

Перегрузка операторов cout and cin
Нужна помощь) Вот что есть: class Dot { public: float x; float y; }; class Circul

При раздельной компиляции не работает перегрузка операторов ввода-вывода
разделил программу и при компиляции компилятор ругается на объявление перегрузки операторов ввода...

После перегрузки операторов не работает cout
Здравствуйте. После использования перегруженного оператора + перестает работать оператор вывода....

Использование функции при выводе в cout
Объясните, пожалуйста, почему так выводит 1 0. int f(int&amp; a){ return ++a; } int main(){ int...

1
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.11.2012, 12:54
Помогаю со студенческими работами здесь

Нет пробелов при выводе в cout
В чем ошибка, почему нету пробелов когда выход проходит в cout? Помогите пожалуйста. #include...

При выводе COUT стирает первую букву
Проблема: при выводе информации о проданных машинах, первая буква названия первой (и только первой,...

Программа аврийно завершается при выводе в cout
Приветствую всех! Начал выполнять задание,связанное с расписанием поездов,но уже в самом начале...

Не работает перегрузка операторов
Не работает перегрузка операторов public static LMatrix operator*(LMatrix a, LMatrix b) ...

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru