declaration in class:
const SalesRegister operator +(const SalesRegister& lhs, const
SalesRegister& rhs);
definition in implementation file:
const SalesRegister SalesRegister::operator+(const SalesRegister
¶m)
{
.....
.....
}
thank you in advance
rappy
You have given it three operands.
> it is
> supposed to add two class operands.
>
Right.
> declaration in class:
> const SalesRegister operator +(const SalesRegister& lhs, const
> SalesRegister& rhs);
>
What you are forgetting is that all class methods have an additional
implicit parameter, the object itself (aka this).
You can define a binary operator inside the class like this
class X
{
X operator+(const X& rhs) const;
};
X X::operator+(const X& rhs) const
{
...
}
Here the implicit parameter is the left hand side operand.
Or you can declare it outside the class like this
class X
{
friend X operator+(const X& lhs, const X& rhs);
};
X operator+(const X& lhs, const X& rhs)
{
...
}
(friendship is optional but usually used).
The outside the class version is usually preferred for symmetrical operators
like +, otherwise you get different argument conversion rules applied to the
left and right hand sides of your operator, which is not a good thing.
john
I have the following declaration in header file class declaration:
const SalesRegister operator +(const SalesRegister&
lhs, const SalesRegister& rhs);
and the following definition in the implementation file:
const SalesRegister operator +(const SalesRegister& lhs, const
SalesRegister& rhs)
{
SalesRegister temp;
temp.totalCostPrice = lhs.GetTotalCostPrice +
rhs.GetTotalCostPrice;
temp.totalSellPrice = lhs.GetTotalSellPrice +
rhs.GetTotalSellPrice;
return temp;
}
and I get this error message: error C2804: binary 'operator +' has too many
parameters, how is this possible
as a binary operator has two operands?
please help me, am I possibly missing a declaration somewhere?
rappy
"Rappy" <rap...@iprimus.com.au> wrote in message
news:40655...@news.iprimus.com.au...
I think you have put the correct declaration in the wrong place.
const SalesRegister operator +(const SalesRegister&
lhs, const SalesRegister& rhs);
Is this inside or outside of the class definition of SalesRegister? It
should be OUTSIDE.
john
Start by creating member function
SalesRegister & SalesRegister::operator*=(SalesRegister const &)
then use non-member function
SalesRegister operator +(
const SalesRegister& lhs, const SalesRegister& rhs)
{
SalesRegister result = lhs;
result += rhs;
return result;
}
Would it be equivalent to make operator+ a static member function?
If the same functionality can be achieved is there ever a reason to prefer a
friend function to a static member function or vice-versa?
Brian F. Seaberg
Naperville, Illinois
Delray Beach, Florida
Yep. If you make it a friend, you get implicit conversions on the lhs.
operator+ can't be a static member, it would have to be a non-static member, and
then you wouldn't get implicit conversions on the lhs.