2 / 2 / 1
Регистрация: 21.03.2015
Сообщений: 72
1

Ошибка undefined reference to `operator<<(std::ostream&, Account)'

27.04.2017, 20:54. Показов 6018. Ответов 5
Метки нет (Все метки)

Всем здравствуйте! На днях столкнулся с ошибкой, с которой еще не раз не сталкивался, и не знаю как ее исправить. Ошибка выглядит так:
|undefined reference to `operator<<(std::ostream&, Account)'|
||error: ld returned 1 exit status|

Как это исправить? И что собственно это за ошибка? Из-за чего она возникает?
Вот собственно мой код.

main.cpp
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
129
130
131
132
133
134
135
#include <iostream>
#include <stdlib.h>
#include "Account.h"
 
using namespace std;
 
int main()
{
    setlocale(0, "");
    Account unit_N1, unit_N2;
    int fige;
 
    std :: cout << std :: endl;
    std :: cout << "Добро пожаловать в программу, которая содержит в себе" << std :: endl;
    std :: cout << " \t\t 2 программы 1.32 и 1.33" << std :: endl;
    std :: cout <<  std :: endl;
 
    std :: cout << "Добро пожаловать пользователь!" << std :: endl;
    std :: cout <<  std :: endl;
    unit_N1.set_personal_data();
    std :: cout << std :: endl;
 
    std :: cout << "Заполним количество купюр российских рублей" << std :: endl;
    std :: cout << "1, 5, 10, 50, 100, 500, 1000, 5000" << std :: endl;
    std :: cout <<  std :: endl;
    std :: cout << "Заполним количество количество копеек" << std :: endl;
    std :: cout << "0.01 (1 копейка), 0.05 (5 копеек), 0.1 (10 копеек), 0.5 (50 копеек) " << std :: endl;
    std :: cout <<  std :: endl;
    std :: cin >> unit_N1;
    std :: cin >> unit_N2;
    std :: cout << std :: endl;
    std :: cout << "Количество номинала первого счета: " << std :: endl;
    unit_N1.get_nominal();
    std :: cout << std :: endl;
    std :: cout << "Количество номинала второго счета: " << std :: endl;
    unit_N2.get_nominal();
    std :: cout << std :: endl;
 
    unit_N1.summa_money_N1();
    unit_N2.summa_money_N2();
 
    for( ; ; ){
        std :: cout << " \t\t - ГЛАВНОЕ МЕНЮ - \t" << std :: endl;
        std :: cout << std :: endl;
        std :: cout << "1 - Смена пользователя." << std :: endl;
        std :: cout << "2 - Вывод на экран полную информацию." << std :: endl;
        std :: cout << "3 - Операция - > сложение." << std :: endl;
        std :: cout << "4 - Операция - > вычитание." << std :: endl;
        std :: cout << "5 - Операция - > умножение." << std :: endl;
        std :: cout << "6 - Операция - > умножение на число." << std :: endl;
        std :: cout << "7 - Перевод валюты в другую сумму." << std :: endl;
        std :: cout << "8 - Вывод суммы прописью." << std :: endl;
        std :: cout << "9 - Операции сравнения" << std :: endl;
        std :: cout << "10 - Выход из программы" << std :: endl;
        std :: cout << std :: endl;
 
        std :: cout << "Ваше действие: ";
        std :: cin >> fige;
 
        switch(fige){
            case 1:{ /// Смена пользователя
                system("cls");
                std :: cout << " \t\t Вы решили сменить пользователя?" << std :: endl;
                std :: cout << std :: endl;
                unit_N1.delete_nominal();
                unit_N2.delete_nominal();
                unit_N1.switch_user();
 
                std :: cout << std :: endl;
                std :: cout << "Заполним количество купюр российских рублей" << std :: endl;
                std :: cout << "1, 5, 10, 50, 100, 500, 1000, 5000" << std :: endl;
                std :: cout << std :: endl;
                std :: cout << "Заполним количество количество копеек" << std :: endl;
                std :: cout << "0.01 (1 копейка), 0.05 (5 копеек), 0.1 (10 копеек), 0.5 (50 копеек) " << std :: endl;
                std :: cout << std :: endl;
                std :: cin >> unit_N1;
                std :: cin >> unit_N2;
                std :: cout << std :: endl;
                std :: cout << "Количество номинала первого счета: " << std :: endl;
                unit_N1.get_nominal();
                std :: cout << std :: endl;
                std :: cout << "Количество номинала второго счета: " << std :: endl;
                unit_N2.get_nominal();
                std :: cout << std :: endl;
 
                system("pause");
                system("cls");
                break;
            }
            case 2:{ /// Вывод на консольно ПОЛНОЙ информации
                system("cls");
                std :: cout << unit_N1.tostring();
                unit_N1.get_money_N1();
                unit_N2.get_money_N2();
                std :: cout << std :: endl;
                std :: cout << " \t Первый номинал количества рублей и копеек: " << std :: endl;
                unit_N1.beautiful_plaque();
                std :: cout << " \t Второй номинал количества рублей и копеек: " << std ::endl;
                unit_N2.beautiful_plaque();
 
                system("pause");
                system("cls");
                break;
            }
            case 3:{ /// Операция сложение
                system("cls");
                int something;
                std :: cout << " \t\t Сложение сумм и номиналов" << std :: endl;
                std :: cout << std :: endl;
                std :: cout << "Вывести информацию о двух кошельках?" << std :: endl;
                std :: cout << "\t 1 - ДА!" << std :: endl;
                std :: cout << "\t 2 - НЕТ!" << std :: endl;
                std :: cin >> something;
                std :: cout << std :: endl;
 
                if(something == 1){
                    unit_N1.beautiful_plaque();
                    unit_N2.beautiful_plaque();
                }
 
                std :: cout << "Результат сложения: " << std :: endl;
                std :: cout << unit_N1 + unit_N2;
 
                system("pause");
                system("cls");
                break;
            }
            case 10:{ /// выход из программы
                return 0;
                break;
            }
        }
    }
    return 0;
}
Account.cpp
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#include "Account.h"
#include <sstream>
#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>
 
/// --------------------- Конструкторы ---------------------
Account :: Account() {
 
}
 
Account :: Account(const Account &other){
    name = other.name;
    number = other.number;
    percent = other.percent;
 
    rub[9] = other.rub[9];
    kop[4] = other.kop[4];
}
 
Account :: Account(string surname, int number, double money, int percent){
 
}
 
Account operator+(Account& v1, Account& v2){
    Account temp;
    for(int i = 0; i < 9; i++ )
        temp.rub[i] = v1.rub[i] + v2.rub[i];
    for(int i = 0; i < 4; i++)
        temp.kop[i] = v1.kop[i] + v2.kop[i];
    return temp;
}
 
Account operator-(Account& v1, Account& v2){
    Account temp;
    for(int i = 0; i < 9; i++ )
        temp.rub[i] = v1.rub[i] - v2.rub[i];
    for(int i = 0; i < 4; i++)
        temp.kop[i] = v1.kop[i] - v2.kop[i];
    return temp;
}
 
Account operator*(Account& v1, Account& v2){
 
}
 
std::istream& operator>>(std::istream& in, Account& m){
    for(int i =0; i < 9; i++){
        m.rub[i] = rand() %5;
    }
    for(int i =0; i < 4; i++){
        m.kop[i] = rand() %5;
    }
    return in;
}
 
std::string Account::tostring() const{
    std::ostringstream oss;
    oss << " \t\t Полная информация о пользователе" << std :: endl;
    oss <<  std :: endl;
    oss << "Фамилия и Имя: " << surname << " " << name << std :: endl;
    oss << "Номер карты: " << number << std :: endl;
    oss << "Имеющийся процент: " << percent << "%" << std :: endl;
    return oss.str();
}
 
void Account :: get_money_N1(){
    std :: cout << "Наличные первого кошелька: " << money_N1 << " руб." << std :: endl;
}
void Account :: get_money_N2(){
    std :: cout << "Наличные второго кошелька: " << money_N2 << " руб." << std :: endl;
}
 
void Account :: beautiful_plaque(){
    std :: cout << "     Количество: " << " \t " << " Номинал: " << std :: endl;
    std :: cout << "Рубли: " << std :: endl;
    for(int i = 0; i < 9; i++){
        std :: cout << i << ". \t " << rub[i] << " \t < --- > \t " << info_rub[i] << " руб." << std :: endl;
    }
    std :: cout << "Копейки: " << std :: endl;
    for(int i = 0; i < 4; i++){
        std :: cout << i << ". \t " << kop[i] << " \t < --- > \t " << info_kop[i] << " коп." << std :: endl;
    }
    std :: cout << "Наличные первого кошелька: " << money_N1 << std :: endl;
    std :: cout << "Наличные второго кошелька: " << money_N2 << std :: endl;
}
 
void Account :: set_personal_data(){
    std :: cout << "Введите Фамилию: ";
    std :: cin >> surname;
    std :: cout << "Введите Имя: ";
    std :: cin >> name;
    std :: cout << "Номер карты: ";
    std :: cin >> number;
    std :: cout << "Начальный взнос первого кошелька: " << money_N1 << std :: endl;
    std :: cout << "Начальный взнос второго кошелька: " << money_N2 << std :: endl;
    std :: cout << "Начальный процент: " << percent << std :: endl;
}
 
void Account :: get_personal_data(){
    std :: cout << "Фам. Имя: \t\t" << surname << " " << name << std :: endl;
    std :: cout << "Номер карты: \t\t" << number << std :: endl;
    std :: cout << "Счет пользователя: \t" << std :: endl;
    std :: cout << " - Первый кошелек: \t" << money_N1 << std :: endl;
    std :: cout << " - Второй кошелек: \t" << money_N2 << std :: endl;
    std :: cout << "Процент: \t\t" << percent << "%" << std :: endl;
}
 
void Account :: get_nominal(){
    std :: cout << "Массив рублей имеет следующий вид: ";
    for(int i =0; i < 9; i++){
        std :: cout << " " << rub[i];
    }
    std :: cout << std :: endl;
    std :: cout << "Массив копеек имеет следующий вид: ";
    for(int i =0; i < 4; i++){
        std :: cout << " " << kop[i];
    }
    std :: cout << std :: endl;
}
void Account :: summa_money_N1(){
    rezult_all = 0;
    rezult_kop = 0;
    rezult_rub = 0;
 
    for(int i = 0; i < 9; i++){
        rezult_rub = rezult_rub + (rub[i] * info_rub[i]);
    }
    for(int i = 0; i < 4; i++){
        rezult_kop = rezult_kop + (kop[i] * info_kop[i]);
    }
    money_N1 = rezult_rub + rezult_kop;
}
 
void Account :: summa_money_N2(){
    rezult_all = 0;
    rezult_kop = 0;
    rezult_rub = 0;
 
    for(int i = 0; i < 9; i++){
        rezult_rub = rezult_rub + (rub[i] * info_rub[i]);
    }
    for(int i = 0; i < 4; i++){
        rezult_kop = rezult_kop + (kop[i] * info_kop[i]);
    }
    money_N2 = rezult_rub + rezult_kop;
}
 
void Account :: switch_user(){
    std :: cout << "Введите Фамилию: ";
    std :: cin >> surname;
    std :: cout << "Введите Имя: ";
    std :: cin >> name;
    std :: cout << "Номер карты: ";
    std :: cin >> number;
    std :: cout << "Начальный взнос: " << std :: endl;
    std :: cout << " - Первый кошелек: \t" << money_N1 << std :: endl;
    std :: cout << " - Второй кошелек: \t" << money_N2 << std :: endl;
    std :: cout << "Начальный процент: " << percent << "%" << std :: endl;
}
 
void Account :: delete_nominal(){
    for(int i = 0; i < 9; i++){
        rub[i] = rub[i] * 0;
    }
    for(int i = 0; i < 4; i++){
        kop[i] = kop[i] * 0;
    }
}
Account.h
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
#ifndef ACCOUNT
#define ACCOUNT
 
#include<string>
#include<iostream>
#include<stdexcept>
 
using namespace std;
 
class Account{
    private:
        string name;    /// Имя владельца
        string surname; /// Фамилия владельца
        int number;     /// Номер банковской карты
        int percent = 2;    /// Начисляемый процент
 
    public:
        double rub[9];      /// Количество номинала рублей
        double kop[4];      /// Колчиество номинала копеек
 
        double money_N1 = 0;      /// Стартовая сумма денег первого кошелька
        double money_N2 = 0;      /// Стартовая сумма денег второго кошельк
        double info_rub[9] = {1, 2, 5, 10, 50, 100, 500, 1000,5000};    /// Информация номинала рублей
        double info_kop[4] = {0.01, 0.05, 0.1, 0.5};                    /// Информация номинала копеек
 
        double rezult_rub, rezult_kop, rezult_all;
 
        Account();                                                  /// По умолчанию
        Account(const Account &other);                              /// Копирующий
        Account(string surname, int number, double money, int percent);   /// С параметром
        Account(double _rub[9], double _kop[4]);
 
        friend std::istream& operator>>(std::istream& in, Account& m);  /// Перегрузка оператора >>
        friend std::ostream& operator<<(std::ostream& h, Account v); /// Перегрузка оператора <<
 
        friend Account operator+(Account& v1, Account& v2); /// Перегрузка оператора +
        friend Account operator/(Account& v1, Account& v2); /// Перегрузка оператора /
        friend Account operator*(Account& v1, Account& v2); /// Перегрузка оператора *
        friend Account operator-(Account& v1, Account& v2); /// Перегрузка оператора -
 
        friend bool operator==(const Account& v1, const Account& v2); /// Перегрузка оператора ==
        friend bool operator>=(const Account& v1, const Account& v2); /// Перегрузка оператора >=
        friend bool operator<=(const Account& v1, const Account& v2); /// Перегрузка оператора <=
        friend bool operator!=(const Account& v1, const Account& v2); /// Перегрузка оператора !=
        friend bool operator<(const Account& v1, const Account& v2); /// Перегрузка оператора <
        friend bool operator>(const Account& v1, const Account& v2); /// Перегрузка оператора >
        std::string tostring() const;                            /// Оформление красивого вывода
 
        void get_personal_data();   /// Вывод персональных данных
        void set_personal_data();   /// Ввод персональных данных
        void get_nominal();         /// Вывод заполненного номинала
        void switch_user();         /// Смена пользователя
        void delete_nominal();      /// Зануление номинала
        void beautiful_plaque();    /// Красивый вывод номинала рублей и копеек
        void summa_money_N1();      /// Расчет суммы unit_N1
        void summa_money_N2();      /// Расчет суммы unit_N2
        void get_money_N1();        /// Вывод суммы unit_N1
        void get_money_N2();        /// Вывод суммы unit_N2
};
 
#endif // ACCOUNT
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
27.04.2017, 20:54
Ответы с готовыми решениями:

Class & operator's |Error: undefined reference to operator
Компилирует нормально, но когда хочу использовать оператор выдает ошибку:undefined reference to...

ostream &operator<< (ostream &output, const Array &obj) - что означает эта строка?
void Array::getArray() // вывод массива { for (int ix = 0; ix &lt; size; ix++) cout &lt;&lt;...

Friend ostream& operator<<(ostream& stream, CArr& obj);
CArr.h #pragma once class CArr{ int* arr = nullptr; int size = 10; void swap(int *a, int...

friend ostream &operator<<(ostream &stream, MyClass o);
Что означает данная строчка которую обычно пишут в конце класса? friend ostream...

5
47 / 28 / 12
Регистрация: 23.01.2013
Сообщений: 125
27.04.2017, 21:06 2
C++
1
 friend std::ostream& operator<<(std::ostream& h, Account v); /// Перегрузка оператора <<
определение потерял
0
2 / 2 / 1
Регистрация: 21.03.2015
Сообщений: 72
27.04.2017, 21:13  [ТС] 3
Не понял. В Account.cpp? Там?
0
nd2
3433 / 2812 / 1249
Регистрация: 29.01.2016
Сообщений: 9,426
27.04.2017, 21:15 4
Цитата Сообщение от zzzLoLzzz Посмотреть сообщение
Из-за чего она возникает?
Компоновщик не видит реализации.
0
47 / 28 / 12
Регистрация: 23.01.2013
Сообщений: 125
27.04.2017, 21:24 5
к слову. ссылку на констатный аккаунт сделай, ибо ты выводишь временный объект когда складываешь два аккаунта std :: cout << unit_N1 + unit_N2;
0
2 / 2 / 1
Регистрация: 21.03.2015
Сообщений: 72
27.04.2017, 21:28  [ТС] 6
Окей! Спасибо ребята! Вроде работает и запускается
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
27.04.2017, 21:28
Помогаю со студенческими работами здесь

Почему friend ostrem& operator <<(ostream& outs, const Rational&); - invalid function declaration?
Пытаюсь скомпилировать программу пишет friend ostrem&amp; operator &lt;&lt;(ostream&amp; outs, const...

Перегрузка бинарного -, ошибка: undefined reference to operator -(.)
Никак не могу понять, в чём же ошибка Вот класс: class tDoubleString { public: char*...

Undefined reference to Rhombus::Rhombus(std::istream &)
Доброго времени суток. При компиляции в чистом g++ возникли три похожие ошибки, аналогичные той,...

Выделение памяти для буффера, под std::istream& operator>>(std::istream &, String &)
Добрый день. Как осуществляется выделения памяти под перегруженный оператор ввода данных в...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Опции темы

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