Click to See Complete Forum and Search --> : Operator Overload problem. Please help
l46kok
October 24th, 2006, 09:22 PM
I have the code as following
#define PRINT_PER_MINUTE 10;
class Printer
{
private:
int pages;
public:
Printer(int _pages)
{
pages = _pages;
}
int getPrintTime()
{
return pages * PRINT_PER_MINUTE;
}
};
bool Printer::operator<=(const Printer& pri)
{
return getPrintTime() <= pri.getPrintTime();
}
and I am getting an error message which states that "<= is not a member of Printer".
What should I do to fix this problem? Please help.
jfaust
October 24th, 2006, 09:28 PM
#define PRINT_PER_MINUTE 10
class Printer
{
private:
int pages;
public:
Printer(int _pages)
{
pages = _pages;
}
int getPrintTime() const
{
return pages * PRINT_PER_MINUTE;
}
};
bool operator<=(const Printer& lhs, const Printer& rhs)
{
return lhs.getPrintTime() <= rhs.getPrintTime();
}
You either need to declare the operator as part of the class or create it as a function. This code declares it as a function. I also fixed some other issues.
Jeff
l46kok
October 24th, 2006, 09:50 PM
Thanks for the reply.
I've tried adding your code, but I still get an error stating
Printer::getPrintTime' : cannot convert 'this' pointer from 'const Printer' to 'Printer &'
What should I do to fix that problem?
jfaust
October 24th, 2006, 10:09 PM
My code compiles. I tried it. Try again.
Jeff
l46kok
October 24th, 2006, 10:14 PM
Oh it worked for me too. Just forgot to put const on my return function. Thanks
exterminator
October 25th, 2006, 01:27 AM
Operator overloading (http://www.codeguru.com/forum/showpost.php?p=1477025&postcount=6)
NMTop40
October 25th, 2006, 03:43 AM
1. Get rid of the #define
2. use explicit constructor and initialiser list:
3. If the operator is overloaded inside a header declare it inline.
4 However you see a wastage because both of the pages variables are being multiplied by a constant so you know a small optimisation to operator<=. However that means accessing the private variable. You therefore declare it first as a friend.
class Printer
{
private:
enum { PRINT_PER_MINUTE = 10 };
int pages;
public:
explicit Printer(int _pages) : pages ( _pages )
{
}
int getPrintTime() const
{
return pages * PRINT_PER_MINUTE;
}
friend bool operator<= ( const Printer & lhs, const Printer & rhs );
};
inline bool operator<=(const Printer& lhs, const Printer& rhs)
{
return lhs.pages <= rhs.pages;
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.