Ошибка компилятора c2679

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2679

Compiler Error C2679

11/04/2016

C2679

C2679

1a5f9d00-9190-4aa6-bc72-949f68ec136f

Compiler Error C2679

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

To use the operator, you must overload it for the specified type or define a conversion to a type for which the operator is defined.

The following sample generates C2679:

// C2679.cpp
class C {
public:
   C();   // no constructor with an int argument
} c;

class D {
public:
   D(int) {}
   D(){}
} d;

int main() {
   c = 10;   // C2679
   d = 10;   // OK
}
  • Kernel.h

    namespace GateServer
    {
        class CKernel
        {
            using PFMsgHandler = std::function<bool(const char * pMsg, int MsgLen)>
        public:
            bool Initialize();
            PFMsgHandler m_MsgHandler[100];
            bool OnMsgFromCS(const char * pMsg, int MsgLen);
        }
    }
    
  • Kernel.cpp

    #include "Kernel.h"
    
    namespace GateServer
    {
        bool CKernel::Initialize()
        {
            m_MsgHandler[0] = &CKernel::OnMsgFromCS; //error
            return true;
        }
    }
    

При попытке скомпилировать программу получаю следующую ошибку:

Error C2679 binary ‘=’: no operator found which takes a right-hand
operand of type ‘bool (__thiscall GateServer::CGSKernel::* )(const
char *,int)’ (or there is no acceptable
conversion) GSKernel c:projectsс++sonicservergateservergskernelgskernel.cpp 28

Arhadthedev's user avatar

Arhadthedev

11.4k8 золотых знаков42 серебряных знака69 бронзовых знаков

задан 3 июн 2017 в 17:50

Tarakan's user avatar

Вы пытаетесь присвоить std::function указателю на член класса.

Решить проблему можно одним из двух способов:

  1. Сделать PFMsgHandler указателем:

    namespace GateServer
    {
        class CKernel
        {
            using PFMsgHandler = bool(GateServer::*)(const char * pMsg, int MsgLen);
    
            // ...
    
  2. Либо заключить указатель внутрь экземпляра std::function:

    #include "Kernel.h"
    
    namespace GateServer
    {
        bool CKernel::Initialize()
        {
            m_MsgHandler[0] = std::bind(
                &CKernel::OnMsgFromCS,
                this,
                std::placeholders::_1,
                std::placeholders::_2
            );
            return true;
        }
    }
    

ответ дан 3 июн 2017 в 18:01

Arhadthedev's user avatar

ArhadthedevArhadthedev

11.4k8 золотых знаков42 серебряных знака69 бронзовых знаков

Нестатические методы класса не являются обычными функциями. В частности, у каждого нестатического метода класса концептуально есть скрытый параметр ClassType *this.

В вашем случае метод CKernel::OnMsgFromCS фактически имеет три параметра: CKernel *this, const char * pMsg и int MsgLen. Вы же пытаетесь засунуть указатель на этот метод в std::function , у которого только два параметра. Поэтому и возникает ошибка.

А уж как эту ошибку исправлять зависит от того, что вы пытаетесь сделать.

ответ дан 3 июн 2017 в 18:05

AnT stands with Russia's user avatar

Есть и 3-й способ решения, для которого нужно немного видоизменить PFMsgHandler:

using PFMsgHandler = std::function<bool(CKernel&, const char * pMsg, int MsgLen)>

И когда будете вызывать экземпляр PFMsgHandler нужно будет передавать объект, для которого функция класса должна быть вызвана, например:

m_MsgHandler[0](*this, "Message", 0);

Конечно, можно в определении PFMsgHandler использовать указатель, а не ссылку, что будет удобнее с this, но будет менее удобно с объектами, которые указателями не являются.

ответ дан 4 июн 2017 в 7:24

ixSci's user avatar

ixSciixSci

23.7k3 золотых знака46 серебряных знаков61 бронзовый знак

  • Remove From My Forums
  • Question

  • Hi Everyone,

    I’m totally new to programming, but I’m trying to learn.  I thought I would reach out to the experts out in the community.  When I compile an old C++ project in Visual Studio 2010 I get a C2679 error.  Like I said, I am total newbee. 
    I bolded and underlined the line that pulls up as the issue.  Here’s a copy of the code:

    Error 40 error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘const auto_orth_case’ (or there is no acceptable conversion) c:documents and settingsbsmith.rmodesktopjoe32updated joe232x  1.0.0.5 release
    20040217includeksfilereader.h 83 1 Joe

    Thanks for the help!

    // KsFileReader.h: interface for the KsFileReader class.
    //
    //////////////////////////////////////////////////////////////////////

    #if !defined(AFX_KSFILEREADER_H__68B53D77_778B_11D1_A97E_0040051E93CB__INCLUDED_)
    #define AFX_KSFILEREADER_H__68B53D77_778B_11D1_A97E_0040051E93CB__INCLUDED_

    #if _MSC_VER >= 1000
    #pragma once
    #endif // _MSC_VER >= 1000

    #include «FileFormatException.h»
    #include «CaseData.h»
    #include «LateralTracing.h»
    #include «FrontalTracing.h»
    #include «ArchTracing.h»

    class KsFileReader {

     struct TempStorage {

      //
      CString m_name; 
      ____  m_sex;
      Race m_race;
      Race m_norm;

      //
      float m_age;
      float m_skeletalAge;
      float   m_height;

      COleDateTime m_birthday, m_xRayDate;
      ArchInfo m_upperArchInfo, m_lowerArchInfo;

      bool    m_bLipsOpen;
      int  m_lateralCount;
      CPoint m_lateralBuffer[169];

      int  m_frontalCount;
      CPoint m_frontalBuffer[123];

      int  m_lowerArchCount;
      CPoint m_lowerArchBuffer[29];

      int  m_upperArchCount;
      CPoint m_upperArchBuffer[29];
     };

     auto_orth_case m_pOrthCase;

    public:
     KsFileReader(CArchive &ar);
     virtual ~KsFileReader() {}

     static bool ReadPatientName(CString& patientName, CArchive& ar);
     void GetOrthCase(auto_orth_case &pCaseFolder) const;

    private:
     // File Reading
     void ProcessCardNo1(TempStorage &tempStorage, PCSTR pszBuf);
     void ProcessCardNo2(TempStorage &tempStorage, PCSTR pszBuf);
     void ProcessTeethInfoCard(TempStorage &tempStorage, PCSTR pszBuf);

     static bool IsDigits(char* pszBuf);
     static int  ReadCardNo(PCSTR pszBuf);

     
     static bool ReadDate(PCSTR pszBuf, COleDateTime &time);
     static int  ParsePointsCard (PCSTR pszBuf, CPoint* pPoints);

     static void AppendPoints(CPoint* pBuffer, int &nCount, 
            const CPoint* pSrc, int nPoints, int nMax);

     // Build Case object
     void ConstructCase(TempStorage &tempStorage);
     LateralTracing* CreateLateral(TempStorage &tempStorage, const PatientTracingInitParam &param) const;
     FrontalTracing* CreateFrontal(TempStorage &tempStorage, const PatientTracingInitParam &param) const;
     ArchTracing* CreateLowerArch (TempStorage &tempStorage, const PatientTracingInitParam &param) const ;
     ArchTracing* CreateUpperArch (TempStorage &tempStorage, const PatientTracingInitParam &param) const ;
    };

    inline void KsFileReader::GetOrthCase(auto_orth_case &pOrthCase) const {
     pOrthCase = m_pOrthCase;
    }

    #endif // !defined(AFX_KSFILEREADER_H__68B53D77_778B_11D1_A97E_0040051E93CB__INCLUDED_)

    • Edited by

      Thursday, December 9, 2010 3:02 PM

Answers

  • Hi Everyone,

    Jinzai sent me a comment, which I don’t see posted here that fixed the issue.  Thanks everyone. 

    Bryan

    …I think that you will have to cast that reference in any event. m_pOrthCase is an auto_orth_case and you have the const modifier to contend with….

    Does this eliminate the error? I tried to recreate a trivial example to test this, but…I did not receive the error that you got and it was not necessary to cast, either. Neither did I receive any
    warnings when I cast the variable that was being set. (I used integers so as to avoid having to create a dummy class in a seperate file.)

    inline void KsFileReader::GetOrthCase(auto_orth_case &pOrthCase) const {
     pOrthCase = (auto_orth_case &)m_pOrthCase;

    The Microsoft Developer Network

    ————————————————————————

    • Marked as answer by
      brjan999
      Thursday, December 16, 2010 4:06 PM

The full error message reads:

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

How can I fix it?

#include <iostream>

using namespace std;

template<class T>
class Dun
{
private:
    T* array{ nullptr };

public:
    Dun(T* _array) : array(_array) {}

    T& Get(int index)
    {
        return this->array[index];
    }
};

template<class T>
class Ar
{
private:
    Dun<T>* data{nullptr};

public:
    Ar(Dun<T>* _data) : data(_data) {}

    T& operator[] (int index)
    {
        return this->data->Get(index);
    }
};

int main()
{
    int a[4] = { 1, 2, 3, 4 };

    auto ar = new Dun<int>(a);
    auto ur = new Ar<int>(ar);

    cout << ur[1];

    return 0;
}

>Solution :

You don’t need pointers here

int main()
{
    int a[4] = { 1, 2, 3, 4 };

    Dun<int> ar{a};
    Ar<int> ur{&ar};

    cout << ur[1];

    return 0;
}

otherwise you’d have to dereference your pointer before your operator[] can be used

cout << (*ur)[1];

  • Forum
  • General C++ Programming
  • C2679 Error I can not solve, would appre

C2679 Error I can not solve, would appreciate help greatly.

Hello!
This is my first time posting here, I hope I am doing so correctly, if not I firmly apologize! I simply am having a lot of trouble with my code and finally hit a breaking point. I have been working on this for hours, and googled heavily, and i think i understand what its saying but I have no idea how to fix it at all.

I am supposed to do code that makes a class template for arrays, and operator overload the information. But whenever I try to check and see if my operator+ overloading works, it says ‘error C2679: binary ‘+’ : no operator found which takes a right-hand operand of type ‘int’ (or there is no acceptable conversion)».

This is my operator+ overloading

(this is in tlist.cpp which has the declaration of the class template and the member functions to it)
TLIST<t_type> & operator+(const TLIST<t_type> & org);
(this is the member function of operator+)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class t_type>
TLIST<t_type> & operator+(const TLIST<t_type> & org)
{
	if (count < capacity)
	{
		DB[count++] = org;
	}
	else
	{
		Double_Size();
		(*this) + org;

	}
}

this is in the other .cpp file which has only the main

1
2
	TLIST<char> Char_List, TempChar1, TempChar2; //default called
	Char_List + 'W' + 'E' + 'L' + 'C' + 'O' + 'M' + 'E';

Could someone tell me what is making it say i cant put an int into the TLIST<int>? I dont know how to fix it, i thought i saw online using ‘const’ would fix it, but i used const, so now i am lost.

Thank you!

> This is my operator+ overloading
> this is the member function of operator+

It should be

operator+=

, shouldn’t it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// member function
template <class t_type> // note: org is of type t_type ( not TLIST<t_type> )
TLIST<t_type>& operator+= ( const t_type & org )
{
	if (count < capacity)
	{
		DB[count++] = org;
                return *this ;
	}
	else
	{
		Double_Size();
		return *this += org;
	}
}


// non-member function
template <class t_type> // note: lst is passed by value
TLIST<t_type> operator+ ( TLIST<t_type> lst, const t_type & org )
{ return lst += org ; }

Last edited on

Oh, well I was told to use operator+. this is an assignment for class, I hope that is ok. They said to overload the + operator, and I tried to do it as they showed in class, but i got that specific error time and time again.

I edited the member function to be += like you showed and got this

C2805: Binary operator += has too few parameters.

Also a C2784 error.

> I edited the member function to be += like you showed and got this

1
2
3
4
5
6
7
// member function
template <class t_type> // note: org is of type t_type ( not TLIST<t_type> )
// TLIST<t_type>& operator+= ( const t_type & org )
TLIST<t_type>& TLIST<t_type>::operator+= ( const t_type & org ) 
{
     // ... 
}

> Also a C2784 error.

The code C2784 won’t be meaningful to someone who does not use the same compiler as you do.
Post the actual text of the error diagnostic.

my apologies!
It was

error C2784: ‘std::reverse_iterator<_RanIt> std::operator +(_Diff,const std::reverse_iterator<_RanIt> &)’ : could not deduce template argument for ‘const std::reverse_iterator<_RanIt> &’ from ‘char’

Ignore that std::reverse_iterator<_RanIt> error. It will go away when the earlier error is fixed.
(The compiler tries to match all possibile operator+ that it can see, one by one).

Alright, I looked, because I have 62 errors and most of them seem to be the C2784 error i mentioned above. 3 of them are C2676 which is
error C2676: binary ‘+’ : ‘TLIST<char>’ does not define this operator or a conversion to a type acceptable to the predefined operator

(the reason there are 3 is because I have the ‘char_list’ used in the main.cpp code 3 times.

1
2
3
	Char_List + 'W' + 'E' + 'L' + 'C' + 'O' + 'M' + 'E';
	Int_List + 1 + 2 + 3 + 4 + 5 + 6 + 7;
	String_List + "hello" + "everyone" + "study" + "hard" + "do not" + "copy" + "learn";

One for each one of those code lines above

2 are C2244
C2244: ‘TLIST<t_type>::operator +=’ : unable to match function definition to an existing declaration

EDIT: Should I post my full code here? I do not mind, but I should say, it is probably bad. I just tried to mimic as the teacher taught, but I am really rough with understanding the concepts, and trying my best to.

Last edited on

Declare the member function (operator+=) in the class

1
2
3
4
5
6
7
8
9
10
template <class t_type>
class TLIST
{
    // ....
 
    public:
       TLIST<t_type>& operator+= ( const t_type & org ) ; // ****

       // ....
};

Define the functions:

1
2
3
4
5
6
7
8
9
template <class t_type> 
TLIST<t_type>& TLIST<t_type>::operator+= ( const t_type & org ) 
{
     // ... 
}

template <class t_type>
TLIST<t_type> operator+ ( TLIST<t_type> lst, const t_type & org )
{ /* ... */; }

Use the functions:

1
2
3
Char_List = Char_List + 'W' + 'E' + 'L' + 'C' + 'O' + 'M' + 'E';
Int_List = Int_List + 1 + 2 + 3 + 4 + 5 + 6 + 7;
String_List = String_List + "hello" + "everyone" + "study" + "hard" + "do not" + "copy" + "learn";

(I presume that you have written a user-defined assignment operator.)

Alright, I added operator+= to the class,
then i defined both functions.

I now have only 3 errors. It says in the class declaration, it says that
TLIST<t_type> & operator+(TLIST<t_type> lst, const t_type & org);

has error C2804 twice, saying «binary operator+ has too many parameters’.

The third error C2676: binary ‘+’ : ‘TLIST<std::string>’ does not define this operator or a conversion to a type acceptable to the predefined operator

Also: I would like to add a quick and sincere THANK YOU for helping me right now. It means a lot to me. I am not sure how much gratitude matters on this forum, but I want to thank you regardless.

Last edited on

Here is my full code if you care to see (incase it helps)
tlist.cpp

EDIT: I hid some code because I was trying to focus on getting the +operator working first. I have no clue if the other stuff works.

Last edited on

operator+ is not a member function; do not declare it in the class. (Just define it outside the class).

(We declare operator+= in the class because it is a member function.)

i removed it from the class, and got a bunch of those errors you said to ignore, and then 2 new errors.

error C2782: ‘TLIST<t_type> operator +(TLIST<t_type>,const t_type &)’ : template parameter ‘t_type’ is ambiguous

error C2676: binary ‘+’ : ‘TLIST<std::string>’ does not define this operator or a conversion to a type acceptable to the predefined operator

String_List + std::string("hello") + std::string("everyone") etc.

After fixing the other errors:

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
#include <iostream>
#include <string>

using namespace std;

template <class t_type>
class TLIST
{

public:

    TLIST();
	~TLIST();
	TLIST( const TLIST<t_type> &); // *** const added
	bool IsEmpty();
	bool IsFull();
	int Search(t_type);
	void Double_Size();
	void Add(t_type item);
	void Remove(const t_type org);
	TLIST<t_type> & operator=(const TLIST<t_type> & org) ;

	TLIST<t_type> & operator+=(const t_type & org);

	friend ostream & operator<<(ostream & out, TLIST<t_type> & org)
	{
		int i;

		for (i = 0; i<org.count; i++)
		{
			out << "DB[i" << i << "] = " << org.DB[i] << endl;
		}
		return out;
	}


private:

	t_type *DB;
	int count;
	int capacity;

};

template <class t_type>
TLIST<t_type>::TLIST()
{
	cout << "You're inside the default constructorn";
	cout << "t_type has size of " << sizeof(t_type) << " bytesnn";
	count = 0;
	capacity = 2;
	DB = new t_type[capacity];

}

template <class t_type>
TLIST<t_type>::~TLIST()
{
	cout << "The destructor has been calledn";
	delete[] DB;
	count = 0;
	DB = 0;
}

template <class t_type>
TLIST<t_type>::TLIST( const TLIST<t_type> & org) // *** const added
{
	count = org.count;
	capacity = org.capacity;
	DB = new t_type[capacity];
	for (int i = 0; i<count; i++)
	{
		DB[i] = org.DB[i];
	}
}


template <class t_type>
int TLIST<t_type>::Search(t_type item)
{
	// int i;
	for (int i = 0; i < count; i++)
	{
		if (item == DB[i])
		{
			return i;
		}
		return -1;
	}
	DB = 0;
}


template <class t_type>
void TLIST<t_type>::Add(t_type item)
{
	if (count < capacity)
	{
		DB[count++] = item;
	}
	else
	{
		Double_Size();
		Add(item);
	}
}

template <class t_type>
bool TLIST<t_type>::IsEmpty()
{
    /*
	if (count == 0)
	{
		return TRUE;
	}
	return FALSE;
	*/
	return count == 0 ;
}

template <class t_type>
bool TLIST<t_type>::IsFull()
{
    /*
	if (count == capacity)
	{
		return TRUE;
	}
		return FALSE;
    */
    return count == capacity ;
}


template <class t_type>
TLIST<t_type> operator+ (TLIST<t_type> lst, const t_type & org)
{
	return lst += org;
}


template <class t_type>
void TLIST<t_type>::Double_Size()
{
	cout << endl << endl;
	cout << "Double_Size has been calledn";
	cout << "Old Size = " << capacity << endl;
	cout << "New Size = " << capacity * 2 << endl;

	capacity *= 2;
	t_type *temp = new t_type[capacity];
	for (int i = 0; i < count; i++)
	{
		temp[i] = DB[i];
	}
	delete[] DB;
	DB = temp;
}

template <class t_type>
TLIST<t_type> & TLIST<t_type>::operator=(const TLIST<t_type> & org)
{
	if (this != &org)
	{
		count = org.count;
		capacity = org.capacity;
		DB = new t_type[capacity];
		for (int i = 0; i < count; i++)
		{
			DB[i] = org.DB[i];
		}
		//return *this;
	}
	return *this ;
}

template <class t_type>
TLIST<t_type>& TLIST<t_type>::operator+= (const t_type & org)
{
	if (count < capacity)
	{
		DB[count++] = org;
		return *this;
	}
	else
	{
		Double_Size();
		return *this += org;
	}
}

// main.cpp
// #include ....

int main()
{
	TLIST<char> Char_List ;
	Char_List = Char_List + 'W' + 'E' + 'L' + 'C' + 'O' + 'M' + 'E';
	std::cout << Char_List << 'n' ;


	TLIST<int> Int_List ;
	Int_List = Int_List + 1 + 2 + 3 + 4 + 5 + 6 + 7;
	std::cout << Int_List << 'n' ;

	TLIST<string> String_List ;
	String_List = String_List + std::string("hello") + std::string("everyone") +
	                            std::string("study") + std::string("hard") +
	                            std::string("do not") + std::string("copy") +
	                            std::string("learn");
	std::cout << String_List << 'n' ;
}

http://coliru.stacked-crooked.com/a/7a7f8ddaa7859325

wow you got it to work! Thank you so so much! I will look over this, and see what you did (I notice the (string) on the strings helped a lot. I need to get ‘remove’ to work. Thank you again! I really owe you so much!

Topic archived. No new replies allowed.

Студворк — интернет-сервис помощи студентам

НЕ давно начал изучать С++. написал программу которая предоставлена в учебники но она у меня что то не компилируется
Вот код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <conio.h>
#include <locale.h>
using namespace std;
int main()
{
    setlocale(LC_ALL,"Rus");
    int i;
    string pr=" ";
    string cur;
    while(cin>>cur)
    {
        ++i;
         if(pr==cur)
             cout<<"Количество слов"<<i<<"pr"<<cur<<endl;
         pr=cur;
    }
 
                                                                    
return 0;
}

Вот ошибки компилятора Microsoft Visual C++ 6.0:
error C2679: binary ‘>>’ : no operator defined which takes a right-hand operand of type ‘class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >’ (or there is no accept
able conversion)

fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.

Помогите их исправить

Понравилась статья? Поделить с друзьями:
  • Ошибка компиляции для платы arduino mega
  • Ошибка компилятора c2665
  • Ошибка компиляции для платы arduino leonardo как исправить
  • Ошибка компилятора c2614
  • Ошибка компиляции для платы arduino genuino uno