Error c2679 бинарный не найден оператор принимающий правый операнд типа

Please don't confuse with the title as it was already asked by someone but for a different context The below code in Visual C++ Compiler (VS2008) does not get compiled, instead it throws this exce...

Please don’t confuse with the title as it was already asked by someone but for a different context

The below code in Visual C++ Compiler (VS2008) does not get compiled, instead it throws this exception:

std::ifstream input (fileName);   

while (input) {
  string s;
  input >> s;
  std::cout << s << std::endl;
};

But this code compiles fine in cygwin g++. Any thoughts?

tmlen's user avatar

tmlen

8,1744 gold badges31 silver badges83 bronze badges

asked Oct 27, 2009 at 14:49

asyncwait's user avatar

0

Have you included all of the following headers?

  • <fstream>
  • <istream>
  • <iostream>
  • <string>

My guess is you forgot <string>.

On a side note: That should be std::cout and std::endl.

answered Oct 27, 2009 at 15:07

sbi's user avatar

sbisbi

217k45 gold badges254 silver badges439 bronze badges

12

Adding to @sbi answer, in my case the difference was including <string> instead of <string.h> (under VS 2017).

See the following answer: similar case answer

Lightness Races in Orbit's user avatar

answered Mar 9, 2018 at 11:35

Guy Avraham's user avatar

Guy AvrahamGuy Avraham

3,3723 gold badges40 silver badges49 bronze badges

In addition to what others said. The following code was necessary in my application to compile succesfully.

std::cout << s.c_str() << std::endl;

Another work-around to this is go to project properties -> General -> Character Set and choose «Ues Multi-Byte Character Set» (You won’t need to use c_str() to output the string)

There’s disadvantages to using MBCS so if you plan to localize your software, I’d advize against this.

answered Oct 24, 2018 at 16:10

Nick Delbar's user avatar

Nick DelbarNick Delbar

1012 silver badges9 bronze badges

include <string>

Try including string header file along with <iostream> file.
It will work in some compilers even without the <string> because settings for different compilers are different and it is the compiler that is responsible for reading the preprocessor files that start with ‘#’ symbol to generate a obj file.

answered Aug 30, 2018 at 16:04

Akshat Bhatt's user avatar

2

I’m required to write a function to overload the ==operator to compare width, height and colour. I need to return ‘Y’ if its equal and ‘N’ if its not.

This is my code which I think is correct, but keeps giving me the error:

error C2679: binary ‘<<‘ : no operator found which takes a right-hand operand of type ‘Rectangle’ (or there is no acceptable conversion)

I’ve searched for an answer and nothing came close to comparing 3 data as most examples are for comparing 2 datas.

#include <iostream>
#include <string>
using namespace std;

class Rectangle
{
private:
    float width;
    float height;
    char colour;
public:
    Rectangle()
    {
        width=2;
        height=1;
        colour='Y';
    }
    ~Rectangle(){}
    float getWidth() { return width; }
    float getHeight() { return height; }
    char getColour() { return colour; }

    Rectangle(float newWidth, float newHeight, char newColour)
    {
        width = newWidth;
        height = newHeight;
        colour = newColour;
    }

    char operator== (const Rectangle& p1){

        if ((width==p1.width) && (height==p1.height) && (colour==p1.colour))
            return 'Y';
        else
            return 'N';
    }
};

int main(int argc, char* argv[])
{
    Rectangle rectA;
    Rectangle rectB(1,2,'R');
    Rectangle rectC(3,4,'B');
    cout << "width and height of rectangle A is := " << rectA.getWidth() << ", " << rectA.getHeight() << endl;
    cout << "Are B and C equal? Ans: " << rectB==rectC << endl;


    return 0;
}

I’m required to write a function to overload the ==operator to compare width, height and colour. I need to return ‘Y’ if its equal and ‘N’ if its not.

This is my code which I think is correct, but keeps giving me the error:

error C2679: binary ‘<<‘ : no operator found which takes a right-hand operand of type ‘Rectangle’ (or there is no acceptable conversion)

I’ve searched for an answer and nothing came close to comparing 3 data as most examples are for comparing 2 datas.

#include <iostream>
#include <string>
using namespace std;

class Rectangle
{
private:
    float width;
    float height;
    char colour;
public:
    Rectangle()
    {
        width=2;
        height=1;
        colour='Y';
    }
    ~Rectangle(){}
    float getWidth() { return width; }
    float getHeight() { return height; }
    char getColour() { return colour; }

    Rectangle(float newWidth, float newHeight, char newColour)
    {
        width = newWidth;
        height = newHeight;
        colour = newColour;
    }

    char operator== (const Rectangle& p1){

        if ((width==p1.width) && (height==p1.height) && (colour==p1.colour))
            return 'Y';
        else
            return 'N';
    }
};

int main(int argc, char* argv[])
{
    Rectangle rectA;
    Rectangle rectB(1,2,'R');
    Rectangle rectC(3,4,'B');
    cout << "width and height of rectangle A is := " << rectA.getWidth() << ", " << rectA.getHeight() << endl;
    cout << "Are B and C equal? Ans: " << rectB==rectC << endl;


    return 0;
}

karlhildekruger

3 / 4 / 0

Регистрация: 09.05.2022

Сообщений: 110

1

05.06.2022, 21:27. Показов 850. Ответов 13

Метки нет (Все метки)


C++
1
2
3
4
        void SerializeInstitute(ofstream& fileStream, Institute imi)
        {
            fileStream << "Course{n" << endl << "Students: " << imi.getStudents() << endl << "Lecturers: " << imi.getLecturers() << endl << "getCourses: " << imi.getCourses() << "getMarks: " << imi.getMarks()  << endl << "}";
        }

Ошибка:

Код

Серьезность	Код	Описание	Проект	Файл	Строка	Состояние подавления
Ошибка	C2679	бинарный "<<": не найден оператор, принимающий правый операнд типа "std::vector<stud::Student,std::allocator<stud::Student>>" (или приемлемое преобразование отсутствует)	204

геттер из класса Institute, который я пытаюсь сериализовать в текстовый файл

C++
1
2
3
4
vector<Student> Institute::getStudents()
{
        return students;
};

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

05.06.2022, 21:27

Ответы с готовыми решениями:

Ошибка C2679: бинарный ‘=’: не найден оператор, принимающий правый операнд типа ‘double’
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include…

Error C2679: бинарный «=»: не найден оператор, принимающий правый операнд типа
Сразу скажу что в с++ полный ноль. Но есть потребность решить такую вот задачу:
Нужно собрать…

Возвращение кортежа — error C2679: бинарный «=»: не найден оператор, принимающий правый операнд типа
Привет
есть функция, которая возвращает кортеж

tuple&lt;X**, Math, int, int,…

Error C2679: бинарный «<<«: не найден оператор, принимающий правый операнд типа «std::string» (или приемлемое
эмулятор работы банкомата
Например

#include &quot;stdafx.h&quot;

#include &lt;iostream&gt;
#include…

Error C2679: бинарный «=»: не найден оператор, принимающий правый операнд
Ошибка 1 error C2679: бинарный &quot;=&quot;: не найден оператор, принимающий правый операнд типа…

13

16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

05.06.2022, 21:48

2

karlhildekruger, вам нужно определить оператор << для типа vector<Student>.



0



karlhildekruger

3 / 4 / 0

Регистрация: 09.05.2022

Сообщений: 110

05.06.2022, 22:23

 [ТС]

3

Это правильно?

C++
1
2
3
4
5
6
7
8
template<class T>
ostream& operator<<(std::ostream& os, const vector<T>& vect)
{
    for (size_t i = 0; i < vect.size(); ++i)
        os << vect[i] << "t";
    os << "n";
    return os;
}

Выдает ошибку

Код

Серьезность	Код	Описание	Проект	Файл	Строка	Состояние подавления
Ошибка	C2679	бинарный "<<": не найден оператор, принимающий правый операнд типа "const _Ty" (или приемлемое преобразование отсутствует)



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

05.06.2022, 23:25

4

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

Это правильно?

Правильно. И для Student тоже должен быть такой оператор.

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

Выдает ошибку

В какой строке?



0



3 / 4 / 0

Регистрация: 09.05.2022

Сообщений: 110

05.06.2022, 23:35

 [ТС]

5

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

os << vect[i] << «t»;

Ошибка в этой строке



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

05.06.2022, 23:59

6

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

Ошибка в этой строке

Цитата
Сообщение от DrOffset
Посмотреть сообщение

для Student тоже должен быть такой оператор



0



karlhildekruger

3 / 4 / 0

Регистрация: 09.05.2022

Сообщений: 110

06.06.2022, 00:12

 [ТС]

7

Не работает. Выводит те же ошибки

C++
1
2
3
4
5
6
7
ostream& operator<<(std::ostream& os, const Student& s)
{
        os << s.getStudentNo();
        os << s.getGroupName();
    os << "n";
    return os;
}



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

06.06.2022, 00:13

8

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

Не работает.

Значит вы что-то не так сделали.
Покажите весь код.



0



karlhildekruger

3 / 4 / 0

Регистрация: 09.05.2022

Сообщений: 110

06.06.2022, 00:16

 [ТС]

9

Student.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
#pragma once
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
#include <vector>
#include "Person.h"
using namespace std;
using namespace per;
namespace stud
{
class Student :public Person
{private:
    string StudentNo = "123";
    string GroupName = "FIIT-21";
 
public:
    void setStudentNo(string newStudentNo);
    void setGroupName(string newGroupName);
    string getStudentNo();
    string getGroupName();
    
};
}
 
#endif

institute.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
#pragma once
#ifndef _INSTITUTE_H_
#define _INSTITUTE_H_
#include <string>
#include <vector>
#include "Student.h"
#include "Lecturer.h"
#include "Course.h"
#include "Mark.h"
using namespace mar;
using namespace cours;
using namespace stud;
using namespace std;
using namespace lect;
namespace insti
{
    class Institute
    {
    private:
        vector<stud::Student>students;
        vector<lect::Lecturer>lecturers;
        vector<cours::Course>courses;
        vector<mar::Mark>marks;
 
    public:
        void AddStudent(stud::Student newStudent);
        vector<Student>GetStudentsGroup(std::string groupName);
        Student GetStudent(std::string studentNo);
        bool DeleteStudent(std::string studentNo);
        void AddEmployee(Lecturer employee);
        Lecturer GetEmployee(int personnelNo);
        bool DeleteEmployee(int personnelNo);
        void AddCourse(Course course);
        Course GetCourse(int id);
        bool DeleteCourse(int id);
        void AddMark(Mark tmpMarks);
        vector<Mark> GetCourseMarks(int courseId);
        vector<Mark> GetStudentMarks(std::string studentNo);
        vector<Mark> GetGroupMarks(std::string groupName);
        vector<Student> getStudents();
        vector<Lecturer> getLecturers();
        vector<Course> getCourses();
        vector<Mark> getMarks();
 
    };
}
 
#endif

serializer.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<fstream>
#include"Person.h"
#include "Institute.h"
#include"Lecturer.h"
#include "Student.h"
#include <string>
#include <vector>
#include"Mark.h"
#include"Course.h"
#include "Institute.h"
using namespace insti;
using namespace per;
using namespace lect;
using namespace stud;
using namespace mar;
using namespace cours;
using namespace std;
 
 
template<class T>
ostream& operator<<(std::ostream& os, const vector<T>& vect)
{
    for (size_t i = 0; i < vect.size(); ++i)
        os << vect[i];
    os << "n";
    return os;
}
 
ostream& operator<<(std::ostream& os, const Student& s)
{
        os << s.getStudentNo();
        os << s.getGroupName();
    os << "n";
    return os;
}
 
 
 
namespace seria
{
 
    class Serializer
    {
    public:
        void SerializePerson(std::ofstream& fileStream, Person person)
        {
            fileStream << "Person{n" << person.get_FIO() << endl << person.get_Email() << endl;
        };
 
 
        Person DeserializePerson(std::ifstream& fileStream)
        {
            
            string s;
            getline(fileStream, s);
            Person person;
            if (s.compare("Person") == 0)
            {
                fileStream >> s; //"{"
                string n;
                fileStream >> n;  
                person.set_FIO(n);
                fileStream >> n;
                person.set_Email(n);
                return person;
            }
        };
 
 
 
 
 
 
 
 
 
        void SerializeLecturer(std::ofstream& fileStream, Lecturer lecturer)
        {
            fileStream << "Lecturer{n" <<"fio: "<< lecturer.get_FIO() << endl<<"email: " << lecturer.get_Email() << endl<<"position: " << lecturer.getPosition() << endl<<"personnelNo: " << lecturer.getPersonnelNo() << "n}";
        };
        Lecturer DeserializeLecturer(std::ifstream& fileStream)
        {
            string s;
            getline(fileStream, s);
            Lecturer lecturer;
            if (s.compare("Lecturer") == 0)
            {
                fileStream >> s; //"{"
                string n;
                fileStream >> n;    //превращение строки в объект (обратная операция сериализации, когда мы заносили объект в текстовый файл)
                lecturer.set_FIO(n);
                fileStream >> n;
                lecturer.set_Email(n);
                fileStream >> n;
                lecturer.setPosition(n);
                int nn;fileStream >> nn;
                lecturer.setPersonnelNo(nn);
                return lecturer;
            }
        };
    
 
 
 
 
 
 
 
 
 
 
 
        void SerializeStudent(std::ofstream& fileStream, Student student)
        {
            SerializePerson(fileStream, student);
            fileStream <<"Group: " << student.getGroupName() << endl <<"Student Number: " << student.getStudentNo() << endl << "}";
        };
 
        Student DeserializeStudent(std::ifstream& fileStream)
        {
 
            /*
            string s;
            getline(fileStream, s);
            Person person;
            if (s.compare("Person") == 0)
            {
                fileStream >> s; //"{"
                string n;
                fileStream >> n;  
                person.set_FIO(n);
                fileStream >> n;
                person.set_Email(n);
                return person;
            }*/
 
 
 
 
            string s;
            getline(fileStream, s);
            Student student;
            if (s.compare("Person") == 0)
            {
                fileStream >> s; //"{"
                string n;
                fileStream >> n;    //фио и мейл уже записаны из Person
                student.setStudentNo(n);
                fileStream >> n;
                student.setGroupName(n);
                return student;
            }
        };
 
 
 
 
 
        void SerializeMark(std::ofstream& fileStream, Mark mark)
        {
            fileStream << "Mark{n" << "year: " << mark.getYear() << endl << "StudentNo: " << mark.getStudentNo() << endl << "Coursed: " << mark.getCourseId() << endl << "Mark: " << mark.getMark() << endl << "}";
        };
        Mark DeserializeMark(std::ifstream& fileStream)
        {
            string s;
            getline(fileStream, s);
            Mark mark;
            if (s.compare("Mark") == 0)
            {
                fileStream >> s; //"{"
                int n;
                fileStream >> n;    //превращение строки в объект (обратная операция сериализации, когда мы заносили объект в текстовый файл)
                mark.setYear(n);
                string s;
                fileStream >> s;
                mark.setStudentNo(s);
                fileStream >> n;
                mark.setCourseId(n);
                fileStream >> n;
                mark.setMark(n);
                return mark;
            }
        };
 
 
 
 
 
 
 
 
 
 
 
 
        void SerializeCourse(std::ofstream& fileStream, Course course)
        {
            Lecturer lecturer;
            fileStream << "Course{n" << "Subject: " << course.getSubject() << endl << "Semester: " << course.getSemester() << endl << "PersonnelNo: " << lecturer.getPersonnelNo() << endl << "}";
        };
        Course DeserializeCourse(std::ifstream& fileStream)
        {
            string s;
            getline(fileStream, s);
            Course course;
            Lecturer lect;
            if (s.compare("Course") == 0)
            {
                fileStream >> s; //"{"
                int n;
                string s;
                fileStream >> s;    //превращение строки в объект (обратная операция сериализации, когда мы заносили объект в текстовый файл)
                course.setSubject(s);
                fileStream >> n;
                course.setSemester(n);
                fileStream >> n;
                lect.setPersonnelNo(n);
                return course;
            }
        };
 
 
        void SerializeInstitute(ofstream& fileStream, Institute imi)
        {
            fileStream  <<imi.getStudents() << endl << "Lecturers: " << imi.getLecturers() << endl << "getCourses: " << imi.getCourses() << "getMarks: " << imi.getMarks() << endl << "}";
 
        }
 
 
 
        Institute DeserializeInstitute(ifstream fileStream)
        {
                string s;
    getline(fileStream, s);
    Institute institute;
    if (s.compare("Institute") == 0)
    {
        
        fileStream >> s; //"{"
         Course c;
         int s;
        fileStream >> s;
        c.setSemester(s);
        institute.AddCourse(c);
 
        Lecturer l;
        string ts;
        fileStream >> ts;
        l.set_FIO(ts);
        institute.AddEmployee(l);
 
        Mark m;
        int fs;
        fileStream >> fs;
        m.setMark(fs);
        institute.AddMark(m);
 
        Student a;
        string ss;
        fileStream >> ss;
        a.set_FIO(ss);
        institute.AddStudent(a);
 
        
        return institute;
    }
};
 
        
 
 
 
 
        //Person DeserializePerson(std::ifstream& fileStream)
        //{
 
        //  string s;
        //  getline(fileStream, s);
        //  Person person;
        //  if (s.compare("Person") == 0)
        //  {
        //      fileStream >> s; //"{"
        //      string n;
        //      fileStream >> n;
        //      person.set_FIO(n);
        //      fileStream >> n;
        //      person.set_Email(n);
        //      return person;
        //  }
        //};
 
 
 
 
    };
}



0



2057 / 1615 / 532

Регистрация: 29.06.2020

Сообщений: 6,077

06.06.2022, 00:32

10

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

os << s.getStudentNo();
        os << s.getGroupName();

Эти методы у класса Student, не константные, а вы пытаетесь их вызвать от константного объекта.
Вот и ошибка.
Если они не изменяют состояния класса, сделайте их константными. (методы класса Student : getStudentNo и getGroupName

Добавлено через 2 минуты

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

string StudentNo = «123»;
    string GroupName = «FIIT-21»;

Улыбнуло )



0



DrOffset

16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

06.06.2022, 00:40

11

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

Выводит те же ошибки

Ну, как минимум не те же.
Судя по коду у вас абсолютно все ваши классы должны быть снабжены соответствующими операторами <<, вы это сделали?
Например, у вас в строке

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

C++
1
fileStream <<imi.getStudents() << endl << "Lecturers: " << imi.getLecturers() << endl << "getCourses: " << imi.getCourses() << "getMarks: " << imi.getMarks() << endl << "}";

getLecturers, getMarks, getCourses приводят к вызову operator<< для Course, Lecturer и Mark. Скорее всего они все у вас отсутствуют.

Также у вас в реализации оператора << для Student используется константная ссылка (что правильно), но функции используемые внутри него string getStudentNo(); и string getGroupName(); объявлены без const. Для остальных классов это тоже видимо будет справедливо. Следите за const-корректностью.



0



3 / 4 / 0

Регистрация: 09.05.2022

Сообщений: 110

06.06.2022, 01:43

 [ТС]

12

сделал для всех операторов определение, все сделал константными, появились другие ошибки

Код

Серьезность	Код	Описание	Проект	Файл	Строка	Состояние подавления
Ошибка	LNK2005	"class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class stud::Student const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBVStudent@stud@@@Z) уже определен в Main.obj	C:УЧЕБАСРСSerializer.obj	1

Код

Серьезность	Код	Описание	Проект	Файл	Строка	Состояние подавления
Ошибка	LNK1169	обнаружен многократно определенный символ - один или более	1



0



Вездепух

Эксперт CЭксперт С++

10435 / 5704 / 1553

Регистрация: 18.10.2014

Сообщений: 14,098

06.06.2022, 02:04

13

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

появились другие ошибки

Ну так в ошибке же написано, в чем проблема.

Скорее всего вы засунули определение оператора << для Student в заголовочный файл. Да, вижу, что так и есть — в serializer.h.

В заголовочный файл можно помещать только определения особых категорий

1. Определения шаблонов
2. Inline определения
3. Определения с внутренним связыванием

Ваш оператор << не принадлежит ни к одной из этих категорий.



0



alecss131

Модератор

Эксперт Java

2383 / 955 / 335

Регистрация: 11.08.2017

Сообщений: 2,980

06.06.2022, 11:18

14

Цитата
Сообщение от karlhildekruger
Посмотреть сообщение

C++
1
2
3
4
5
6
7
8
template<class T>
ostream& operator<<(std::ostream& os, const vector<T>& vect)
{
 for (size_t i = 0; i < vect.size(); ++i)
 os << vect[i] << "t";
 os << "n";
 return os;
}

Зачем так сложно? можно короче

C++
1
2
3
4
5
6
template<class T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vect) {
 std::copy(vect.begin(), vect.end(), std::ostream_iterator<T>(std::cout, "t"));
 os << std::endl;
 return os;
}



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

06.06.2022, 11:18

14

  • Remove From My Forums
  • Question

  • When i am trying to port my project from visual studio 2006 to visual studio 2008, i am getting the following error

    error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘util:Stick out tongueoint *’ (or there is no acceptable conversion)

    1> C:Program FilesMicrosoft Visual Studio 9.0VCincludevector(273): could be ‘std::_Vector_const_iterator<_Ty,_Alloc> &std::_Vector_const_iterator<_Ty,_Alloc>:Surpriseperator =(const std::_Vector_const_iterator<_Ty,_Alloc> &)’

    Can any one help me in resolving the error

Answers

  • Maybe you have to replace the last line with:

        lp_Iterator = lpC_Line->Points.end();

  • Are you sure there are «()» after end in your last code? Maybe you also have to define your iterator as a constant one:

    std:: vector<util:: Point>:: const_iterator lp_Iterator;

Hi everyone, I’m new to C++. I’ve been assigned the following tasks.
1. Choose any two random numbers in the range 3 to 9.
2. Find position of these random numbers for each row.
3. Swap these two random numbers for each row.
4. Display new vector after swapping.

I tried to solve it but error occurred.
Error:
error C2679: binary ‘<<‘: no operator found which takes a right-hand operand of type ‘std::vector<int,std::allocator<_Ty>>’ (or there is no acceptable conversion)

I don’t know how to fix it. Hopefully someone can help me. Thank you :)

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
#include <iostream>     // cout
#include <ctime>		// time
#include <cstdlib>		// srand, rand()
#include <algorithm>    // find(), iter_swap()
#include <vector>       // vector

using namespace std;

int main()
{
	// Initialize random seed:
	srand(time(NULL));

	vector< vector<int> > vec =
	{
		{ 9, 8, 7, 6, 5, 4, 3, 2, 1 },
		{ 1, 2, 3, 4, 5, 6, 7, 8, 9 },
		{ 5, 4, 3, 2, 1, 9, 8, 7, 6 }
	};

	// Print Original Vector
	cout << "Original vector :" << endl;
	for (size_t i = 0; i < vec.size(); i++)
	{
		for (size_t j = 0; j < vec[i].size(); j++)
		{
			cout << vec[i][j] << " ";
		}
		cout << "n";
	}
	
	// Generate two random number in the range 3 to 9
	int r1, r2;
	do {
		r1 = rand() % 9 + 3;      // r1 in the range 3 to 9
		r2 = rand() % 9 + 3;	// r2 in the range 3 to 9
	} while (r1 == r2);

	cout << "First random number = " << r1 << endl;
	cout << "Second random number = " << r2 << endl;

	// Iterator used to store the position of searched element
	

	for (size_t i = 0; i < vec.size(); i++)
	{
		vector <vector<int> >::iterator it, ik;

		// Find position of first random number, r1
		it = find(vec.begin(), vec.end(), r1);
		if (it != vec.end())
		{
			cout << "First random number " << r1 << " was found at position ";
			cout << it - vec.begin() + 1 << "n";
		}
		else
			cout << "Number not found.nn";

		// Find position of second random number, r2
		ik = find(vec.begin(), vec.end(), r2);
		if (ik != vec.end())
		{
			cout << "Second random number " << r2 << " was found at position ";
			cout << ik - vec.begin() + 1 << "n";
		}
		else
			cout << "Number not found.nn";

		// Swap them
		if (it != vec.end() && ik != vec.end())
		{
			cout << "Swapping random numbers " << *it << " and " << *ik << 'n';
			iter_swap(it, ik);
		}

		// Print New Vector
		cout << "New vector :";
		for (size_t i = 0; i < vec.size(); i++)
		{
			for (size_t j = 0; j < vec[i].size(); j++)
			{
				cout << vec[i][j] << " ";
			}
			cout << "n";
		}
	}

	return 0;
}

Here:

 
cout << "Swapping random numbers " << *it << " and " << *ik << 'n';

The type of it is std::vector<std::vector<int>>::iterator, so the type of *it is std::vector<int>.

Are you sure the rest of the code in the loop does what you think it does? What it really does is not swap two numbers. It’s swapping two vectors; two rows, if you will.

Because you have a vector of vectors, your iterators are pointing to an entire vector of values, not a single value … so the << operator won’t know how to output them.

Perhaps you would like to explain exactly how you think «your» code works?

I think it would be easier to advise if you gave us VERBATIM the bit of your assignment BEFORE what you have quoted: we are only getting a very confused story and it is unclear what you are being asked.

HiHelios,

Are you sure the rest of the code in the loop does what you think it does? What it really does is not swap two numbers. It’s swapping two vectors; two rows, if you will.

Can’t I use iter_swap() function to swap numbers?

Hilastchance,

I think it would be easier to advise if you gave us VERBATIM the bit of your assignment BEFORE what you have quoted: we are only getting a very confused story and it is unclear what you are being asked.

Sorry for inconvenience. I was given a task to generate two random numbers between 3 to 9.
For example: first random number = 5 and second random number = 9.

Then, I need to find the position of these random number for each row vector as follow:
{ 9, 8, 7, 6, 5, 4, 3, 2, 1 } —> first random number = position 5, second random number = position 1
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } —> first random number = position 5, second random number = position 9
{ 5, 4, 3, 2, 1, 9, 8, 7, 6 } —> first random number = position 1, second random number = position 6.

Then, swap these random numbers for each row
{ 9, 8, 7, 6, 5, 4, 3, 2, 1 } —> { 5, 8, 7, 6, 9, 4, 3, 2, 1 }
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } —> { 1, 2, 3, 4, 9, 6, 7, 8, 5 }
{ 5, 4, 3, 2, 1, 9, 8, 7, 6 } —> { 9, 4, 3, 2, 1, 5, 8, 7, 6 }

You need to deal with each vec[i] in turn, not the whole of vec.

I presume you know whether the number refers to the value or its position.

Last edited on

Hi lastchance,

You need to deal with each vec[i] in turn, not the whole of vec.

Does it mean I need to deal with each column not each row.

Sorry for asking. A bit confusing..

Does it mean I need to deal with each column not each row.

You need to deal with both.

sarah1993 wrote:
Does it mean I need to deal with each column not each row.

You need to deal with the i’th row (that, is, vec[i]) inside the i loop.

1
2
3
		vector <vector<int> >::iterator it, ik;
		// Find position of first random number, r1
		it = find(vec.begin(), vec.end(), r1);

needs to be

1
2
3
		vector<int>::iterator it, ik;
		// Find position of first random number, r1
		it = find(vec[i].begin(), vec[i].end(), r1);

with a whole mass of other changes from vec to vec[i] below it.

For your final output either move it outside the i loop, or just do one row vector at a time.

Your random numbers are currently in the range 3 to 11, not 3 to 9.

Last edited on

Hi lastchance and helios, thank you for your advise.

I’ve improved this codes based on your explanation and it worked. Thank you so much for helping. I really appreciated it.

Topic archived. No new replies allowed.

Member Avatar

13 Years Ago

Hi!

I try to implement a matrix template class which inherits the vector of vectors.
The message I get: «error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘const Vector<T> *’ (or there is no acceptable conversion)» (When I call the alternate matrix constructor, at the line «this = &h;».)
Any thoughts…? Thanks a lot in advance.

vectorTemplate.h:

#ifndef _VECTOR_TEMPLATE_H
#define _VECTOR_TEMPLATE_H

#include <iostream>
#include <fstream>

//#include "complex.h"

template<class T>
class Vector 
{ private:
	int num; // Number of elements
   	T* pdata; // Pointer to the data
	void Init(int Num); // private function since user should not call it
					// only for the member functions to call
 public:
   	Vector(); // default constructor
   	Vector(int Num); // alternate constructor
   	Vector(const Vector& v); // copy constructor
   	~Vector(); // destructor
	int GetNum() const; // access function
   	Vector<T>& operator= (const Vector<T>& v); //  overloaded assignment operator
   	T& operator[] (int i) const; // overloaded array access operator
   	template<class T> friend std::istream& operator>>(std::istream& is, Vector<T>& v);// keyboard input
   	template<class T> friend std::ostream& operator<<(std::ostream& os, Vector<T>& v);// screen output
   	template<class T> friend std::ifstream& operator>>(std::ifstream& ifs, Vector<T>& v);// file input
   	template<class T> friend std::ofstream& operator<<(std::ofstream& ofs, Vector<T>& v);// file output
 };

// default constructor
template<class T>
Vector<T>::Vector() : num(0), pdata(0) {}

// initialise data, called by the constructors
template<class T>
void Vector<T>::Init(int Num)
{
	num = Num;
  	if (num <= 0)
     		pdata = 0;  // Object construction failed!
   	else
  		pdata = new T[num];  // Allocate memory for vector
}

// alternate constructor 
template<class T>
Vector<T>::Vector(int Num)
{
	Init(Num);
}

// copy constructor
template<class T>
Vector<T>::Vector(const Vector& copy) {
Init(copy.GetNum()); // allocate the memory 

// copy the data members
if (pdata) for (int i=0; i<num; i++) pdata[i]=copy.pdata[i]; 
}



// destructor
template<class T>
Vector<T>::~Vector()
{
   	delete [] pdata; // free the dynamic memory 
}



// assignment operator 
template<class T>
Vector<T>& Vector<T>::operator=(const Vector& copy)
{
if (this == &copy) return *this; // Can't copy self to self (that is v = v 
// in main is dealt with)
   	delete [] pdata; // delete existing memory
   	Init(copy.GetNum()); // create new memory then copy data
  	if (pdata) for (int i=0; i<copy.GetNum(); i++) pdata[i] = copy.pdata[i]; 

  	return *this;
}



// array access operator
template<class T>
T& Vector<T>::operator[](int i) const
{
   	if (i < 0) 
     		i = 0;  // Range error causes index to equal 0
			// should really throw an exception
   	return pdata[i];
}



// return the size of the vector
template<class T>
int Vector<T>::GetNum() const
{
  	return num;
}

 

// keyboard input 
template<class T>
std::istream& operator>>(std::istream& is, Vector<T>& v) {
  	int Num;

   	std::cout << "input the size for the vectorn";
     	is >> Num;

     	// create a temporary Vector object of correct size
     	Vector<T> temp(Num);

	// input the elements
     	std::cout << "input the vector elementsn";
  	for (int i=0; i<Num; i++) is >> temp[i];

	// copy temp into v
	v = temp;

	// return the stream object
  	return is;
}

// file input
template<class T>
std::ifstream& operator>>(std::ifstream& ifs, Vector<T>& v)
{
     	int Num;

	// read size from the file
     	ifs >> Num;

	// create a temporary Vector object of correct size
     	Vector<T> temp(Num);

	// input the values
     	for (int i=0; i<Num; i++) ifs >> temp[i];

	// copy temp into v
	v = temp;

	// return the file stream object
  	return ifs;
}
// screen output
template<class T>
std::ostream& operator<<(std::ostream& os, Vector<T>& v)
{
   	if (v.pdata) {
     		os << "The vector elements aren";
     		for (int i=0; i<v.GetNum(); i++) os << v[i]  << "n";
   	}
  	return os;
}
// file output
template<class T>
std::ofstream& operator<<(std::ofstream& ofs, Vector<T>& v)
{
   	if (v.pdata) {
     		ofs << "The vector elements aren";
     		for (int i=0; i<v.GetNum(); i++) ofs << v[i]  << "n";
   	}
  	return ofs;
}

#endif

matrixTemplate.h:

#ifndef _MATRIX_TEMPLATE_H
#define _MATRIX_TEMPLATE_H

#include <iostream>//
#include <fstream>//
#include "vectorTemplate.h"

//#include "complex.h"

template<class T>
class Matrix : public Vector< Vector<T> >{
public:
Matrix(); // default constructor, uses default constructor for v
Matrix(int Nrows, int Ncols);  // alternate constructor
//T& operator() (int i, int j) const; //  function call overload (-,-)
template<class T> friend Matrix<T> operator*(const Matrix<T>& m1, const Matrix<T>& m2); // overload * for matrix multiplication
template<class T> friend std::istream& operator>>(std::istream& is, Matrix<T>& m);// keyboard input
template<class T> friend std::ostream& operator<<(std::ostream& os, Matrix<T>& m);// screen output
template<class T> friend std::ifstream& operator>>(std::ifstream& ifs, Matrix<T>& m);// file input
template<class T> friend std::ofstream& operator<<(std::ofstream& ofs, Matrix<T>& m);// file output
};

template<class T>
Matrix<T>::Matrix() : Vector< Vector<T> >()/*, nrows(0), ncols(0)*//*, Vector() */{}// default constructor, uses default constructor for v

template<class T>
Matrix<T>::Matrix(int Nrows, int Ncols) : Vector< Vector<T> >(Nrows)/*Vector< Vector<T> >()*//*, nrows(Nrows)*//*, ncols(Ncols)*//*, Vector(Nrows)*/  // alternate constructor
{
	for (int i = 0; i < Nrows; i++)
	{
		/*const Vector<T>* d = new Vector<T>(Ncols);
		this[i] = d;*/
		Vector<T>* d = new Vector<T>(Ncols);
		const Vector<T> h = *d;
		this[i] = &h;
		//this[i] = new Vector<T>(Ncols);
		//this[i] = *(new Vector<T>(Ncols));//this[i] = &(*(new Vector<T>(Ncols)));//this[i] = *(new Vector<T>(Ncols));
	}
}

template<class T>
Matrix<T> operator*(const Matrix<T>& m1, const Matrix<T>& m2) 
// overload * for matrix multiplication
{
	
	if (m1[0].GetNum() == m2.GetNum())
	{	
		Matrix<T> m3(m1.GetNum() , m2[0].GetNum());
		for (int i = 0; i < m1.GetNum(); i++)
		{
			for (int j = 0; j < m2[0].GetNum(); j++)
			{
				
				for (int k = 0; k < m1[0].GetNum(); k++)
				{
					if (k == 0) m3[i][j] = m1[i][k] * m2[k][j];
					else m3[i][j] = m3[i][j] + m1[i][k] * m2[k][j];
				}
			}
		}
		return m3;
	}
	else
	{
		std::cout << "input matrices are not multicablen";
		return m1;
	}
}

//screen input
template<class T>
std::istream& operator>>(std::istream& is, Matrix<T>& m) {
	int Nrows, Ncols;

	// input the size of the matrix
     	std::cout << "input num of rows and columnsn";
     	is >> Nrows >> Ncols;
     	
// create a temporary matrix of the correct size
     	Matrix<T> temp(Nrows, Ncols);
	
      std::cout << "input the matrix elementsn";
  	for (int i=0; i<Nrows; i++) 
	{
		for (int j=0 ; j<Ncols; j++) 
		{std::cout << "hi";
			is >> temp[i][j];std::cout << "ha";
		}
	}
	
     	// copy temp to m
     	m = temp;
	return is;
}

// file input
template<class T>
std::ifstream& operator>>(std::ifstream& ifs, Matrix<T>& m)
{
     	int Nrows, Ncols;

	// read size from the file
     	ifs >> Nrows >> Ncols;

    // create a temporary Matrix object of correct size
     	Matrix<T> temp(Nrows, Ncols);

	// input the values

	for (int i=0; i<Nrows; i++) 
for (int j=0 ; j<Ncols; j++) ifs >> temp[i][j];

     	// copy temp to m
     	m = temp;

  	// return the file stream object
		return ifs;
}

// screen output
template<class T>
std::ostream& operator<<(std::ostream& os, Matrix<T>& m)
{
   	if (m.GetNum() > 0) {
     		os << "The matrix elements aren";
     		for (int i=0; i<m.GetNum(); i++) 
			{
				if (m[0].GetNum() > 0) 
				{
					for (int j=0; j<m[0].GetNum(); j++) 
					{
						os << m[i][j]  << "n";
					}
				}
			}
   	}
  	return os;
}
// file output
template<class T>
std::ofstream& operator<<(std::ofstream& ofs, Matrix<T>& m)
{
   	if (m.GetNum() > 0) {
     		ofs << "The matrix elements aren";
     		for (int i=0; i<m.GetNum(); i++) 
			{
				if (m[0].GetNum() > 0) 
				{
					for (int j=0; j<m[0].GetNum(); j++) 
					{
						ofs << m[i][j]  << "n";
					}
				}
			}
   	}
  	return ofs;
}

#endif


Recommended Answers

Can you explain why did you wrote this absolutely senseless expression: this[i] = &h ? If you want inherited operator[] , write (*this)[i]

Jump to Post

It’s of no importance. What did you want to do there — that is a question.

Jump to Post

All 5 Replies

Member Avatar


ArkM

1,090



Postaholic


13 Years Ago

Can you explain why did you wrote this absolutely senseless expression: this[i] = &h ? If you want inherited operator[] , write (*this)[i]

Member Avatar

13 Years Ago

Can you explain why did you wrote this absolutely senseless expression: this[i] = &h ? If you want inherited operator[] , write (*this)[i]

I tried many combinations (some of them are still there as comments), among them this[i] = new Vector<T>(Ncols); too. (*this)[i] = new Vector<T>(Ncols); is not working either.

Member Avatar


ArkM

1,090



Postaholic


13 Years Ago

It’s of no importance. What did you want to do there — that is a question.

Member Avatar


daviddoria

334



Posting Virtuoso



Featured Poster


13 Years Ago

Why post 500 lines of code? Can you simplify the code to < 20 lines so we can look at it?

Member Avatar


xth

0



Newbie Poster


12 Years Ago

how did you solve the problem?


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

>
Ошибки компилирования Visual studio 2010
, error C2679: бинарный «<<«: не найден оператор, принимающий правый операнд типа «void»

  • Подписаться на тему
  • Сообщить другу
  • Скачать/распечатать тему



Сообщ.
#1

,
05.10.10, 21:36

    С++ начал токо изучать по книги и при попытке напечать один из примеров выдала Visual Studio 2010 выдал ошибку и скомпилировать не смог.
    Ошибка — error C2679: бинарный «<<«: не найден оператор, принимающий правый операнд типа «void»
    На одном из форумов в инете, нашел похожую проблему у человека с такой же ошибкой, правда код программы тама другой.

    Цитата groundhog

    Объясню, что написл Slip — cout не перегружен для работы с void-типами, и это нормально, это в логике вещей, нельзя вывести то, чего нет. А твоя функция возвращает void тип, который ты и пытаешься вывести. Следовательно, чтобы убрать эту ошибку нужно вызывать твою функцию вне cout;

    И сообственно как мне сделать так что бы эта тестовая программа у меня заработала?

    ExpandedWrap disabled

      #include <iostream>

      #include <string>

      using namespace std;

      class studentList

      {

      public:

          //структура

          studentList (string name)

          {   setInstitutName (name); }

          //три функции

          void setInstitutName(string name)

          {   institutName = name; }

          string getInstitutName()

          {   return institutName; }

          void displayInstitutName()

          {   cout << getInstitutName() << endl; }

      private:

          string institutName;

      };

      int main ()

      {  

          studentList student1 ( «one» );

          studentList student2 ( «two» );

          cout << student1.displayInstitutName() << student2.displayInstitutName() << endl; //здесь ошибка

          system(«pause»);

          return 0;

      }

    —— Построение начато: проект: firstProgram, Конфигурация: Debug Win32 ——
    Построение начато 06.10.2010 1:22:36.
    InitializeBuildStatus:
    Обращение к «DebugfirstProgram.unsuccessfulbuild».
    ClCompile:
    test.cpp
    d:work filesvisual studio 2010 c++ filesfirstprogramfirstprogramtest.cpp(29): error C2679: бинарный «<<«: не найден оператор, принимающий правый операнд типа «void» (или приемлемое преобразование отсутствует)
    c:program files (x86)microsoft visual studio 10.0vcincludeostream(679): может быть «std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)»
    with
    [
    _Elem=char,
    _Traits=std::char_traits<char>
    ]
    c:program files (x86)microsoft visual studio 10.0vcincludeostream(726): или «std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)»
    with
    [

    ….

    c:program files (x86)microsoft visual studio 10.0vcincludeostream(487): или «std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::basic_streambuf<_Elem,_Traits> *)»
    with
    [
    _Elem=char,
    _Traits=std::char_traits<char>
    ]
    при попытке сопоставить список аргументов «(std::ostream, void)»

    СБОЙ построения.

    Затраченное время: 00:00:02.20
    ========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

    Сообщение отредактировано: FIZy — 05.10.10, 21:36

    Wizard

    B.V.



    Сообщ.
    #2

    ,
    05.10.10, 21:42

      Ну, так убери эту строчку, и оставь только вызовы функций

      ExpandedWrap disabled

        cout << student1.displayInstitutName() << student2.displayInstitutName() << endl; //здесь ошибка

      Или перепиши displayInstitutName, что бы она ничего не выводила и возвращала результат в basic_string


      FIZy



      Сообщ.
      #3

      ,
      05.10.10, 21:47

        И вправду убрал тип void у displayInstitutName и сказал возратить значение)

        ExpandedWrap disabled

              string displayInstitutName()

              {   return getInstitutName(); }

        2B.V. Спасибо)

        Добавлено 05.10.10, 22:01
        Хотя в идеале наверное лучше так.

        ExpandedWrap disabled

          #include <iostream>

          #include <string>

          using namespace std;

          class studentList

          {

          public:

              //структура

              studentList (string name)

              {   setInstitutName (name); }

              //три функции

              void setInstitutName(string name)

              {   institutName = name; }

              string getInstitutName()

              {   return institutName; }

              void displayInstitutName()

              {   cout << getInstitutName(); }

          private:

              string institutName;

          };

          int main ()

          {  

              studentList student1 ( «one» );

              studentList student2 ( «two» );

              student1.displayInstitutName();

              student2.displayInstitutName();

              system(«pause»);

              return 0;

          }

        Сообщение отредактировано: FIZy — 05.10.10, 22:02

        0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

        0 пользователей:

        • Предыдущая тема
        • Visual C++ / MFC / WTL
        • Следующая тема

        [ Script execution time: 0,0411 ]   [ 16 queries used ]   [ Generated: 9.02.23, 12:12 GMT ]  

        Понравилась статья? Поделить с друзьями:
      • Error c2601 main недопустимые локальные определения функций
      • Error c2589 illegal token on right side of
      • Error c2563 mismatch in formal parameter list
      • Error c2561 main функция должна возвращать значение
      • Error c2504 не определен базовый класс