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 };
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.2k10 gold badges49 silver badges62 bronze badges
1
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||
1 |
||||
21.11.2016, 22:18. Показов 2994. Ответов 15 Метки нет (Все метки)
Добрый вечер. Нужно в с++ cli сделать перегрузку <<. Подскажите пожалуйста, правильный синтаксис:
0 |
shilko2013 257 / 234 / 185 Регистрация: 02.04.2016 Сообщений: 898 |
||||
21.11.2016, 22:31 |
2 |
|||
0 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
21.11.2016, 22:40 [ТС] |
3 |
Я так пробовала, в CLI как-то по другому должно быть,т.к там нет &
0 |
805 / 532 / 158 Регистрация: 27.01.2015 Сообщений: 3,017 Записей в блоге: 1 |
|
21.11.2016, 22:40 |
4 |
shilko2013, ошибочка во втором параметре
0 |
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||
22.11.2016, 00:10 [ТС] |
5 |
|||
error C3699: &: это косвенное обращение невозможно использовать для типа «const Phone» Добавлено через 1 час 21 минуту
0 |
moskitos80 289 / 95 / 40 Регистрация: 04.10.2011 Сообщений: 329 |
||||||||
22.11.2016, 00:29 |
6 |
|||||||
Вот же вам правильно подсказали:
а у вас:
— найдите отличия.
0 |
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||||||
22.11.2016, 00:42 [ТС] |
7 |
|||||||
Я и так,и так пробовала
В файл.срр пишу
Ошибки:
0 |
moskitos80 289 / 95 / 40 Регистрация: 04.10.2011 Сообщений: 329 |
||||||||||||
22.11.2016, 00:59 |
8 |
|||||||||||
Теперь понятно вы пытаетесь поместить перегрузку оператора << прямо в класс Phone — так у вас не выйдет. Я так понял вы хотите выводить Phone в поток ostream. Вам для этого внутри оператора нужны оба операнда, причем левый из них должен быть ostream — при перегрузке оператора, как члена класса — так не получится. Если вы помещаете перегрузку в класс, то автоматом левым операндом становится this и метод будет принимать только один аргумент — правый операнд. Вам нужно перегружать оператор как отдельную функцию: в .h файле после объявления класса Phone:
далее в .cpp файле можно там же где и определения методов Phone:
если внутри определения оператора << нужен доступ к закрытым членам Phone, то объявляйте в объявлении класса Phone в .h файле
надеюсь понятно объяснил
1 |
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||||||||||||||
22.11.2016, 01:47 [ТС] |
9 |
|||||||||||||||
Сделала как Вы написали , все равно не работает…
А с << проблемы.
Ошибки Может в C++ CLI вообще невозможно перегрузить этот оператор?
0 |
DrOffset 17427 / 9259 / 2264 Регистрация: 30.01.2014 Сообщений: 16,215 |
||||||||
22.11.2016, 09:07 |
10 |
|||||||
Вот же вам правильно подсказали Неправильно.
Причина ошибки была не в этом.
&: это косвенное обращение невозможно использовать для типа «const Phone» Причина в том, что Phone — это managed класс. И его невозможно использовать со ссылкой (т.к. обычно она реализуется через указатель на низком уровне, а в CLI обычные указатели для managed типов не используются). Поэтому компилятор предлагает для оператора вот такую форму:
Поэтому предлагаю больше не смотреть в сторону перестановки местами амперсанда в параметре функции — это тупиковый вариант. PS. На форуме есть специальный раздел для CLI.
0 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
22.11.2016, 10:52 [ТС] |
11 |
Cделала так как Вы написали
0 |
17427 / 9259 / 2264 Регистрация: 30.01.2014 Сообщений: 16,215 |
|
22.11.2016, 11:04 |
12 |
Вероника99, покажи место в коде, где возникает ошибка.
0 |
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||||||
22.11.2016, 11:08 [ТС] |
13 |
|||||||
Если дописывать friend
.h(27): error C3809: Phone: управляемый тип не может иметь дружественные функции, классы и интерфейсы
0 |
DrOffset 17427 / 9259 / 2264 Регистрация: 30.01.2014 Сообщений: 16,215 |
||||
22.11.2016, 11:12 |
14 |
|||
Вероника99, ну так надо же понимать разницу записи с friend и без…
Phone: управляемый тип не может иметь дружественные функции, классы и интерфейсы Вот эту ошибку сразу надо было показывать
при этом, естественно, доступ в ней будет только к публичным функциям и данным класса.
1 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
22.11.2016, 11:30 [ТС] |
15 |
Помогло, спасибо, до inline не додумалась бы)
0 |
GbaLog- |
22.11.2016, 12:26
|
Не по теме:
и еще бесконечность Кликните здесь для просмотра всего текста
Бесконечность не предел!
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
22.11.2016, 12:26 |
Error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::istream» Error C2678: бинарный «<<«: не найден оператор, принимающий левый операнд типа «std::ifstream»
Шаблоны класса:Матрица. Ошибка бинарный «=»: не найден оператор, принимающий правый операнд типа «Matr<T>» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 16 |
I am making a custom matrix class with templates for educational purposes. I want my class
to work in the following way:
mat*2; //Works
2*mat; //Should also work
For the first case I have the following declaration
matrix<T> operator*(const T& a) const;
and implemenetation
template <typename T>
matrix<T> matrix<T>::operator*(const T& a) const{
//Implementation here
}
While for the second case I have to make the implementation as a non member class
matrix<T> operator*(T& a, matrix<T>& mat);
with the implementation
template<typename T>
matrix<T> operator*(T& a, const matrix<T>& mat){
return mat*a;
}
however when I try to compile this I get the following error using MSVC
error C2804: binary 'operator *' has too many parameters
..main.cpp(33): error C2678: binary '*' : no operator found which takes a left hand operand of type 'int' (or there is no acceptable conversion)
Перейти к контенту
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
- Изменено