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
nfnicolas 3 / 3 / 0 Регистрация: 07.02.2016 Сообщений: 140 |
||||
1 |
||||
Ошибка в перегрузке оператора29.10.2016, 21:13. Показов 3431. Ответов 3 Метки нет (Все метки)
Не пойму в чем дело(( Имеется класс вектор ,вычислил длину,а теперь очу сравнить их величины,но не могу составить данный оператор выдает ошибку
__________________
0 |
Peoples 1623 / 953 / 782 Регистрация: 06.02.2016 Сообщений: 2,449 Записей в блоге: 30 |
||||
29.10.2016, 21:20 |
2 |
|||
Сообщение было отмечено nfnicolas как решение РешениеЕсли перегрузка описывается снаружи класса, то указывается два параметра, если внутри, то только один
2 |
181 / 47 / 33 Регистрация: 27.02.2016 Сообщений: 260 |
|
29.10.2016, 21:21 |
3 |
nfnicolas, из параметров, там необходим только один. Вторым является объект класса, чей оператор вызывается.
1 |
2549 / 1208 / 358 Регистрация: 30.11.2013 Сообщений: 3,826 |
|
29.10.2016, 21:25 |
4 |
nfnicolas, ознакомьтесь с этой темой — Как правильно перегружать операторы?
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
29.10.2016, 21:25 |
4 |
I’m learning about class operators and am stuck. I’m trying a simple class that defines an x,y point. The code then multiplies the x and y values of that point by 4 and spits out the new values. When I compile this, I get the following error on the line in bold:
«error C2804: binary ‘operator *’ has too many parameters»
Here is the code:
// 13.1.2.cpp : main project file.
#include «stdafx.h»
#include <iostream>
using namespace std;
class Point {
private:
int x,y; //Data Members
public:
//Constructors
Point() {x=0; y=0;}
Point(int new_x, int new_y) {set(new_x, new_y);}
Point(const Point &src) {set(src.x, src.y);}
//Operations
Point mult(const int &n, const Point &pt);
Point operator*(const int n, Point &pt) {return mult(n, pt);}
//Other member functions
void set(int new_x, int new_y);
int get_x() const {return x;}
int get_y() const {return y;}
};
int main()
{
Point point1(20, 25); //Create a new Point objects
Point point2 = 4 * point1; //Create another new point that is 4x the value of point1
cout << «The value of point2 is » << point2.get_x();
cout << «, » << point2.get_y() << «.» << endl << endl;
system(«PAUSE»);
return 0;
}
void Point::set(int new_x, int new_y) {
x = new_x;
y = new_y;
}
Point Point::mult(const int &n, const Point &pt) {
Point new_pt;
new_pt.x = n * pt.x;
new_pt.y = n * pt.y;
return new_pt;
}
Does anyone see why this is happening? Thanks!
OK….you have a few mistakes. I don’t know whether you know this but… Your operator* definition is wrong. When you call it like you did here:Point point2 = 4 * point1;
compiler turns that intopoint1.operator*(4);
which, of course, doesn’t match parameters declared in operator* prototype. Operator* is binary, which means it needs 2 operands, and because you declared it within class Point (not as global function), you don’t need to pass object explicitly. So:
|
|
Thank you. I’m not surprised about the multiple mistakes. One other mistake that I made was not explaining the point of the exercise that I am working on. This is an exercise that has two objectives: 1) to learn about global / friend functions and 2) about improving efficiency with references. So, I need to keep those ideas in my code, even though I don’t think that I did with my original post.
I’m totally confused about how to do this, and I think that the book that I am studying does a terrible job explaining it. Can somebody see what I am doing wrong in my original code with these two ideas?
Thanks again!
- 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
-
Изменено
Stub
-
#1
When I try to overload the == operator, it gives me an «error C2804: binary
‘operator ==’ has too many parameters.»
bool operator==(const Store& Store1, const Store& Store2);
After Adding keyword, friend, to the above declaration, the error disappear.
Of course there’re 3 parameters involved in this newly defined == operator.
I am trying to understand why the compiler complains about too many
parameters for the declaration. Is this due to that the original ==operator
takes only 2 parameters? What is this declaration conflicting with
actually?
Could someone help me to understand this? Thanks!
Advertisements
Victor Bazarov
-
#2
Stub said:
When I try to overload the == operator, it gives me an «error C2804: binary
‘operator ==’ has too many parameters.»bool operator==(const Store& Store1, const Store& Store2);
After Adding keyword, friend, to the above declaration, the error disappear.
Of course there’re 3 parameters involved in this newly defined ==
operator.
What do you mean «of course»? You cannot redefine the number of
the operands an operator takes. Equality (like inequality or
multiplication, or division, or comparison) operator takes _two_
and _precisely__two_ operands. A non-static member function for
an overloaded binary (two-operand) operator MUST have only one
[non-hidden] argument. A non-member function for a binary op
needs EXACTLY two operands.
I am trying to understand why the compiler complains about too many
parameters for the declaration. Is this due to that the original ==operator
takes only 2 parameters?
Yes.What is this declaration conflicting with
actually?Could someone help me to understand this? Thanks!
Well, I guess you just need to find a decent C++ book and read
the chapter on operator overloading. Try not to guess how
a language works. Learn instead.
Victor
David White
-
#3
Stub said:
When I try to overload the == operator, it gives me an «error C2804: binary
‘operator ==’ has too many parameters.»bool operator==(const Store& Store1, const Store& Store2);
After Adding keyword, friend, to the above declaration, the error
disappear.
I assume this is inside a class definition. You didn’t say so.
There are always 2 parameters to operator==, because it is intended for an
expression of the form op1 == op2. For a class member function, *this (the
object for which the operator is called) is implicitly the first of the
parameters, so the member function takes one parameter (for the second
operand). Example:
class A
{
int n;
public:
A(int n_) : n(n_) {}
bool operator==(const A &a) const
{
return n == a.n;
}
};
void f()
{
A a1(1), a2(2);
if(a1 == a2)
{
//…
}
}
a1 == a2 above is the same as: a1.operator==(a2).
If the function is outside the class, it will take two arguments, one for
each operand, because there is no *this outside the class. You declare it as
a friend inside the class only if you need the function to access private or
protected members. Example:
class A
{
friend bool operator==(const A &a1, const A &a2);
int n;
public:
A(int n_) : n(n_) {}
};
bool operator==(const A &a1, const A &a2)
{
return a1.n == a2.n;
}
Of course there’re 3 parameters involved in this newly defined == operator.
I am trying to understand why the compiler complains about too many
parameters for the declaration. Is this due to that the original ==operator
takes only 2 parameters?
An operator== will always take 2 parameters.
What is this declaration conflicting with
actually?
No conflict. It’s just wrong for an operator== to take more or less than 2
parameters (including implicit *this, where applicable).
DW
Advertisements
DarkSpy
-
#4
When I try to overload the == operator, it gives me an «error C2804: binary
‘operator ==’ has too many parameters.»bool operator==(const Store& Store1, const Store& Store2);
After Adding keyword, friend, to the above declaration, the error disappear.
Of course there’re 3 parameters involved in this newly defined == operator.
I am trying to understand why the compiler complains about too many
parameters for the declaration. Is this due to that the original ==operator
takes only 2 parameters? What is this declaration conflicting with
actually?Could someone help me to understand this? Thanks!
in member function, operator== just need one parameter, because
the left value is *this, the parameter in bracket is the
right value of operator== for ex:
struct A { bool operator==(int i) {…} };
A a; if(a == 10) …
means: a.operator==(10);
for friend keyword, this is not member functions, and no * this
in the function implicit, so need two parameter, but need a
class object or enum type for one parameter, the parameter
in bracket is:
friend bool operator==(the left value of expression, the right value
of expression)
for ex:
struct A { friend bool operator==(int i, const A &) {…} };
A a; if(10 == a) …
means: operator==(10, a);
[comp.lang.c++]
[comp.lang.c++.moderated]
DarkSpy, A C++ Mad Dog.
I wrote a c++ code as follows:
#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;
}
On compilation it is giving first error as:
error: C2804: binary 'operator <' has too many parameters
and so many other error in class LessComparer.
I’m new to such overloading. Please help me in correcting the code.
Thanks.
LessComparer needs to implement operator() not operator<
bool operator()( const data& a1, const data& a2 ) const
Записывая свой собственный векторный класс (для игрового движка) и перегружая оператор ‘+’ в проекте Visual Studio 2013 CPlusPlus (используя VC runtime 120), он вызывает ошибку компилятора:
Ошибка: слишком много параметров для этой операторской функции.
Фрагмент кода из Vector.hpp
файл ниже.
Vector.hpp
class Vector
{
private:
double i;
double j;
double k;
public:
Vector(double _i, double _j, double _k)
{
i = _i;
j = _j;
k = _k;
}
Vector& operator+=(const Vector& p1)
{
i += p1.i;
j += p1.j;
k += p1.k;
return *this;
}
//Some other functionality...
Vector operator+(const Vector& p1, Vector& p2) //Error is thrown here...
{
Vector temp(p1);
return temp += p2;
}
};
Что я здесь не так делаю? Не хочу, чтобы мой оператор перегружал функцию, не являющуюся членом.
3
Решение
когда operator+
определяется внутри класса, левый операнд оператора является текущим экземпляром. Итак, чтобы объявить перегрузку operator+
у вас есть 2 варианта
- внутри класса, только с одним параметром, который является правым операндом
- вне класса, с двумя параметрами, левый и правый операнды.
Выбор 1: вне класса
class Vector
{
private:
double i;
double j;
double k;
public:
Vector(double _i, double _j, double _k)
{
i = _i;
j = _j;
k = _k;
}
Vector& operator+=(const Vector& p1)
{
i += p1.i;
j += p1.j;
k += p1.k;
return *this;
}
//Some other functionality...};
Vector operator+(const Vector& p1, const Vector& p2)
{
Vector temp(p1);
temp += p2;
return temp;
}
Выбор 2: внутри класса
class Vector
{
private:
double i;
double j;
double k;
public:
Vector(double _i, double _j, double _k)
{
i = _i;
j = _j;
k = _k;
}
Vector& operator+=(const Vector& p1)
{
i += p1.i;
j += p1.j;
k += p1.k;
return *this;
}Vector operator+(consr Vector & p2)
{
Vector temp(*this);
temp += p2;
return temp;
}
};
Вы можете увидеть, как должны быть объявлены операторы здесь: Операторы C / C ++
10
Другие решения
Еще одна возможность — использование ключевого слова friend.
friend Vector operator+(const Number& n1, const Number& n2)
{
Vector temp(n1);
temp+=n2;
return temp;
}
0
|
|
|
Опять шаблоны классов
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
const bool operator == (const cilindr<T> &a1 ,const cilindr<T> &a2) { if(a1.radius == a2.radius) return true; else return false; } почему ошыпки? Цитата error C2804: binary ‘operator ==’ has too many parameters |
mo3r |
|
Цитата Koss @ 01.01.07, 15:37 почему ошыпки? Ты объявляешь оператор как функцию-член. В этом случае надо писать только один аргумент у оператора (правый операнд, а this будет левым операндом), либо же делать статический оператор. |
Koss |
|
bool operator == (const cilindr<T> &a2) { if(*this.radius == a2.radius) return true; else return false; } переделал-работае Добавлено 01.01.07, 16:01 |
mo3r |
|
Цитата Koss @ 01.01.07, 15:57 а как правильней писать? Практически, без разницы. Дело вкуса. |
Unreal Man |
|
Цитата Koss @ 01.01.07, 15:57 bool operator == (const cilindr<T> &a2) Эх…
bool operator == (const cylinder &a) const { return radius == a.radius; } |
panaslonik |
|
а ведь в начальном коде надо было изменить всего одно слово
friend bool operator == (const cilindr<T> &a1 ,const cilindr<T> &a2) { if(a1.radius == a2.radius) return true; else return false; } |
J0ker |
|
template <typename T> const bool operator == (const cilindr<T> &a1 ,const cilindr<T> &a2) { if(a1.radius == a2.radius) return true; else return false; } по-моему, так |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0405 ] [ 16 queries used ] [ Generated: 9.02.23, 12:12 GMT ]