I am a beginner in programming I learn operator And i have a problem with operator== in Visul studio I get the error :C2804 binary ‘operator ==’ has too many parameters
Duree.cpp
#include "Duree.h"
#include<iostream>
Duree::Duree(int h,int m,int s) :
m_h(h),m_m(m),m_s(s)
{
}
bool Duree::estEgal(Duree const& b) const {
return (m_h == b.m_h && m_m == b.m_m && m_s == b.m_s);
}
bool operator==(Duree const& a, Duree const& b)
{
return a.estEgal(b);
}
Duree.h
#ifndef DUREE_H_INCLUDED
#define DUREE_H_INCLUDED
class Duree
{
public:
Duree(int h = 0,int m = 0,int s = 0);
bool estEgal(Duree const& b) const;
bool operator==(Duree const& a, Duree const& b);
private:
int m_h;
int m_m;
int m_s;
};
#endif
main.cpp
#include <iostream>
#include "Duree.h"
using namespace std;
int main()
{
Duree a(10,10,10),b(20,20,20);
cout << "Hello world! " << endl;
if (a == b) {
cout << "a = b";
}
return 0;
}
Error C2804 binary ‘operator ==’ has too many parameters
Error C2676 binary ‘==’: ‘Duree’ does not define this operator or a conversion to a type acceptable to the predefined operator cplusplus
Error C2804 binary ‘operator ==’ has too many parameters cplusplus
Error (active) E0349 no operator "==" matches these operands cplusplus
Severity Code Description Project File Line Suppression State
Error C2804 binary ‘operator ==’ has too many parameters cplusplus C:\Users\ACER\source\repos\cplusplus\cplusplus\Duree.h 12
Error C2676 binary ‘==’: ‘Duree’ does not define this operator or a conversion to a type acceptable to the predefined operator cplusplus C:\Users\ACER\source\repos\cplusplus\cplusplus\cplusplus.cpp 11
Error C2804 binary ‘operator ==’ has too many parameters cplusplus C:\Users\ACER\source\repos\cplusplus\cplusplus\Duree.h 12
Error (active) E0349 no operator "==" matches these operands cplusplus C:\Users\ACER\source\repos\cplusplus\cplusplus\cplusplus.cpp 11
>Solution :
If you define the operator as non-static member function, there is one additional "hidden parameter": this.
For this reason operators implemented as non-static member functions must take only a single parameter: The second operand of the operator.
class Duree
{
public:
Duree(int h = 0, int m = 0, int s = 0);
bool operator==(Duree const& b) const
{
return (m_h == b.m_h && m_m == b.m_m && m_s == b.m_s);
}
private:
int m_h;
int m_m;
int m_s;
};
...
Duree a;
Duree b;
//the following 2 rhs expressions are the same
bool b1 = (a == b);
bool b2 = a.operator==(b);
You could also add the implement an operator at namespace scope inside the class body by making the operator a friend:
class Duree
{
public:
Duree(int h = 0, int m = 0, int s = 0);
friend bool operator==(Duree const& a, Duree const& b)
{
return (a.m_h == b.m_h && a.m_m == b.m_m && a.m_s == b.m_s);
}
private:
int m_h;
int m_m;
int m_s;
};
// the operator definition above basically has the same effect as defining
//
// inline bool operator==(Duree const& a, Duree const& b)
//
// here + adding it as a friend of the Duree class