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
11.4k8 золотых знаков42 серебряных знака69 бронзовых знаков
задан 3 июн 2017 в 17:50
Вы пытаетесь присвоить std::function
указателю на член класса.
Решить проблему можно одним из двух способов:
-
Сделать
PFMsgHandler
указателем:namespace GateServer { class CKernel { using PFMsgHandler = bool(GateServer::*)(const char * pMsg, int MsgLen); // ...
-
Либо заключить указатель внутрь экземпляра
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
ArhadthedevArhadthedev
11.4k8 золотых знаков42 серебряных знака69 бронзовых знаков
Нестатические методы класса не являются обычными функциями. В частности, у каждого нестатического метода класса концептуально есть скрытый параметр ClassType *this
.
В вашем случае метод CKernel::OnMsgFromCS
фактически имеет три параметра: CKernel *this
, const char * pMsg
и int MsgLen
. Вы же пытаетесь засунуть указатель на этот метод в std::function
, у которого только два параметра. Поэтому и возникает ошибка.
А уж как эту ошибку исправлять зависит от того, что вы пытаетесь сделать.
ответ дан 3 июн 2017 в 18:05
Есть и 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
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 JoeThanks 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 ¶m) const;
FrontalTracing* CreateFrontal(TempStorage &tempStorage, const PatientTracingInitParam ¶m) const;
ArchTracing* CreateLowerArch (TempStorage &tempStorage, const PatientTracingInitParam ¶m) const ;
ArchTracing* CreateUpperArch (TempStorage &tempStorage, const PatientTracingInitParam ¶m) 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
-
Edited by
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
-
Marked as answer by
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+)
|
|
this is in the other .cpp file which has only the main
|
|
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?
|
|
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
|
|
> 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.
|
|
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
|
|
Define the functions:
|
|
Use the functions:
|
|
(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:
|
|
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++ | ||
|
Вот ошибки компилятора 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.
Помогите их исправить