Here is my class:
#ifndef CLOCK_H
#define CLOCK_H
using namespace std;
class Clock
{
//Member Variables
private: int hours, minutes;
void fixTime( );
public:
//Getter & settor methods.
void setHours(int hrs);
int getHours() const;
void setMinutes(int mins);
int getMinutes() const;
//Constructors
Clock();
Clock(int);
Clock(int, int);
//Copy Constructor
Clock(const Clock &obj);
//Overloaded operator functions
void operator+(const Clock &hours);
void operator+(int mins);
void operator-(const Clock &hours);
void operator-(int minutes1);
ostream &operator<<(ostream &out, Clock &clockObj); //This however is my problem where i get the error C2804. Saying that it has to many parameters
};
#endif
All this function is supposed to do is out the values of a clock at different times.
![]()
asked Apr 3, 2013 at 2:37
2
ostream &operator<<(ostream &out, Clock &clockObj);
should be
friend ostream &operator<<(ostream &out, Clock &clockObj);
According to Stanley et al’s C++ Primer (Fourth Edition pp 514):
When we define an input or output operator that conforms to the
conventions of the iostream library, we must make it a nonmember
operator. We cannot make the operator a member of our own class. If we
did, then the left-hand operand would have to be an object of our
class type
Therefore, it is good practice to overload << and >> as friend functions of the class.
answered Apr 3, 2013 at 2:41
![]()
taocptaocp
23.1k10 gold badges49 silver badges60 bronze badges
1
| description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
|---|---|---|---|---|---|
|
Learn more about: Compiler Error C2804 |
Compiler Error C2804 |
11/04/2016 |
C2804 |
C2804 |
b066e563-cca4-450c-8ba7-3b0d7a89f3ea |
Compiler Error C2804
binary ‘operator operator’ has too many parameters
The overloaded binary operator member function is declared with more than one parameter. The first operand parameter of a binary operator member function, whose type is the operator’s enclosing type, is implied.
Examples
The following sample generates C2804 and shows how to fix it.
// C2804.cpp // compile by using: cl /c /W4 C2804.cpp class X { public: X& operator+= (const X &left, const X &right); // C2804 X& operator+= (const X &right); // OK - left operand implicitly *this }; int main() { X x, y; x += y; // equivalent to x.operator+=(y) }
The following sample generates C2804 and shows how to fix it.
// C2804_2.cpp // compile with: /clr /c ref struct Y { Y^ operator +(Y^ hY, int i); // C2804 static Y^ operator +(Y^ hY, int i); // OK Y^ operator +(int i); // OK };
Trying to implement operator overloading using the following code:
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator+ (Number<T>&, const Number<T> &);
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Number<T> Number<T>::operator+ (Number<T>& lhs, const Number<T> & rhs) {
return lhs.value + rhs.value;
}
Trying to emulate similar examples found online, but this attempt generates several compiler errors
-
‘{‘ missing function header (old-style format list?)
-
binary ‘operator +’ has too many parameters
-
class template «Number» has no member «operator+»
Number<T> Number<T>::operator+ (Number<T>& lhs, const Number<T> & rhs)
With all the decisions: whether or not to include «<T>«; whether or not to use references for sends and returns; whether or not to use «const» and/or «friend»; and whether or not to use «this», «new» and/or «->»; it’s confusing enough to search for outside help :).
Any idea what (many things) I’m doing wrong?
Thanks for your consideration
asked Jan 24, 2022 at 4:15
1
You’re forgetting about the implicit this parameter that are present as the first parameter in a non-static member function.
To solve your probelm just remove the extra first parameter from operator+ as shown below:
template<typename T>
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator+ (const Number<T> &);//REMOVED UNNECESSARY PARAMETER
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Number<T> Number<T>::operator+ (const Number<T> & rhs) { //REMOVED UNNECESSARY PARAMETER
return value + rhs.value;//CHANGED lhs.value to value
}
The output of the program can be seen here.
answered Jan 24, 2022 at 4:20
![]()
Jason LiamJason Liam
31.8k5 gold badges21 silver badges52 bronze badges
0
Remove this line:
Number<T> operator+ (Number<T>&, const Number<T> &);
and define operator+ out of the class body this way:
template<typename T>
Number<T> operator+(Number<T> const& lhs, Number<T> const& rhs) {
auto ret{ lhs };
ret.value += rhs.value;
return ret;
}
answered Jan 24, 2022 at 4:56
Trying to implement operator overloading using the following code:
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator+ (Number<T>&, const Number<T> &);
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Number<T> Number<T>::operator+ (Number<T>& lhs, const Number<T> & rhs) {
return lhs.value + rhs.value;
}
Trying to emulate similar examples found online, but this attempt generates several compiler errors
-
‘{‘ missing function header (old-style format list?)
-
binary ‘operator +’ has too many parameters
-
class template «Number» has no member «operator+»
Number<T> Number<T>::operator+ (Number<T>& lhs, const Number<T> & rhs)
With all the decisions: whether or not to include «<T>«; whether or not to use references for sends and returns; whether or not to use «const» and/or «friend»; and whether or not to use «this», «new» and/or «->»; it’s confusing enough to search for outside help :).
Any idea what (many things) I’m doing wrong?
Thanks for your consideration
asked Jan 24, 2022 at 4:15
1
You’re forgetting about the implicit this parameter that are present as the first parameter in a non-static member function.
To solve your probelm just remove the extra first parameter from operator+ as shown below:
template<typename T>
class Number
{
T value;
public:
Number(T v);
Number();
Number<T> operator+ (const Number<T> &);//REMOVED UNNECESSARY PARAMETER
T getValue() { return value; };
};
template <typename T>
Number<T>::Number(T val):value(val) { }
template <typename T>
Number<T> Number<T>::operator+ (const Number<T> & rhs) { //REMOVED UNNECESSARY PARAMETER
return value + rhs.value;//CHANGED lhs.value to value
}
The output of the program can be seen here.
answered Jan 24, 2022 at 4:20
![]()
Jason LiamJason Liam
31.8k5 gold badges21 silver badges52 bronze badges
0
Remove this line:
Number<T> operator+ (Number<T>&, const Number<T> &);
and define operator+ out of the class body this way:
template<typename T>
Number<T> operator+(Number<T> const& lhs, Number<T> const& rhs) {
auto ret{ lhs };
ret.value += rhs.value;
return ret;
}
answered Jan 24, 2022 at 4:56
Вопрос:
Я написал код c++ следующим образом:
#include<iostream>
#include<string>
#include<set>
using namespace std;
class data{
int i;
float f;
char c;
public:
data();
data(int i,float f,char c);
};
data::data(int i,float f,char c){
this->i=i;
this->f=f;
this->c=c;
};
class LessComparer{
bool operator<( const data& a1, const data& a2 ) const{
return( a1.i < a2.i ||
(!(a1.i > a2.i) && (a1.f < a2.f)) ||
(!(a1.i > a2.i) && !(a1.f > a2.f) && (a1.c < a2.c)));
}
};
int main(){
set<data,LessComparer> s;
set<data,LessComparer>::iterator it;
s.insert(data(1,1.3,'a'));
s.insert(data(2,2.3,'b'));
s.insert(data(3,3.3,'c'));
if((it=s.find(data(1,1.3,'a'))!=s.end())
cout<<(*it).i;
cin.get();
return 0;
}
При компиляции она дает первую ошибку:
error: C2804: binary 'operator <' has too many parameters
и так много других ошибок в классе LessComparer.
Я новичок в такой перегрузке. Пожалуйста, помогите мне в исправлении кода.
Благодарю.
Ответ №1
LessComparer необходимо реализовать operator() not operator <
bool operator()( const data& a1, const data& a2 ) const
Ответ №2
Если вы объявите оператор < operator внутри класса, первым параметром будет неявно this.
Чтобы объявить это с помощью 2 параметров, вы должны сделать это вне контекста класса.
Ниже сравнивает объект типа LessComparer на объект типа data.
class LessComparer{
bool operator < ( const data& a2 ) const{
//...
}
};
Если вы хотите сравнить два объекта data, объявите оператор внутри class data или вне класса с двумя параметрами:
class data{
public:
bool operator < ( const data& a2 ) const{
//...
}
};
исключающее
class data
{
//...
};
bool operator<( const data& a1, const data& a2 ){
//...
}
- Remove From My Forums
-
Вопрос
-
Hey Folks,
I wonder if someone could answer this…
Here’s the interface of an oversimplified Matrix class…
template<typename T>
class Matrix {
public:
Matrix() {}
~Matrix() {}
Matrix<T>& Matrix<T>::operator=(Matrix<T>&&);
friend const Matrix<T> operator+(const Matrix<T>&, const Matrix<T>&);
friend ostream& operator<<(ostream&, Matrix<T>&);
private:
vector<vector<T>> _mat;
};No problems when I implement the equality operator…
template<typename T>
Matrix<T>& Matrix<T>::operator=(Matrix<T>&& other) {
swap(_mat, other._mat);
return *this;
}No problems when I implement the dump-to-output-stream operator…
template<typename T>
ostream& operator<<(ostream& os, Matrix<T>& mat) {
ostream_iterator<T> out(os, » «);
vector<T> vec(0);
for (int i = 0; i < mat.Rows(); ++i) {
vec = mat.getRow(i);
copy(vec.begin(), vec.end(), out);
os << endl;
}
return os;
}But, when implementing the plus operator outside the interface…
template<typename T>
const Matrix<T> Matrix<T>::operator+(const Matrix<T>& left, const Matrix<T>& right) {
// …
Matrix<T> res;
return res;
}Compiler gives me…
error C2039: ‘+’: is not a member of ‘Matrix<T>’
And removing the ‘friend’ prefix results in…
error C2804: binary ‘operator +’ has too many parameters.
I can get it to compile and work properly if the definition is stated inside the class interface.
I’ve used a General -> Empty project.
By the way, the compiler being used is the latest — Visual C++ Compiler November 2013 CTP.
Any thoughts as to why this is happening?
Ответы
-
your operator + is not a member of Matrix<T>, it is a friend. So drop the Matrix<T>:: qualifier.
Edit: Also, you need to use a different template parameter on the friend declaration:
template<typename U>
friend const Matrix<U> operator +(const Matrix<U>&, const Matrix<U>&);
David Wilkinson | Visual C++ MVP
-
Изменено
1 октября 2014 г. 8:48
-
Предложено в качестве ответа
Wyck
1 октября 2014 г. 13:54 -
Помечено в качестве ответа
May Wang — MSFT
14 октября 2014 г. 1:43
-
Изменено