Re: operator overloading simple question
On Mar 27, 10:49 am, Sam Hu <SamHu.Sa...@gmail.com> wrote:
Dir Sirs,
This is just a question from a C++ newbie regarding the operator
overloading.Since I do not want to use friend key word,I write class
graduate as below:
//graduate.h
#ifndef GRADUATE_H
#define GRADUATE_H
#include <iostream>
#include <string>
using namespace std;
class graduate
{
public:
/** Default constructor */
graduate();
string getDegree() const;
bool isEqual(const graduate& rhs);
bool lessThan(const graduate& rhs);
These two member functions should be declared as const, because they
will not modify *this.
istream& getfrom(istream& istr)const;
This member function must NOT be declared as const.
ostream& sendto(ostream& ostr)const;
protected:
As there are no protected members, you can leave this line out.
private:
string name;
string degree;};
bool operator==(const graduate& lhs,graduate& rhs)
For symmetry, and because neither operand will get changed, you should
declare both parameters as const (reference).
{
return lhs.isEqual(rhs);}
bool operator<(const graduate& lhs,graduate& rhs)
Same here.
{
return lhs.lessThan(rhs);
}
istream& operator>>(istream& istr,const graduate& grad)const
Both consts here are an error.
The 'const graduate& grad' is an error, because you actually want to
change the object with the information you read from the stream.
The const at the end is an error, because your operator>> is not a
member function, and const in that position is only allowed for member
functions.
{
return grad.getfrom(istr);}
ostream& operator<<(ostream& ostr,const graduate& grad)const
Same problem with the const at the end.
{
return grad.sendto(ostr);}
graduate::graduate()
{
//ctor}
/** @brief getDegree
*
* @todo: document this function
*/
string graduate::getDegree() const
{
return degree;
}
/** @brief getfrom
*
* @todo: document this function
*/
istream & graduate::getfrom(istream& istr)const
As said before, this function should be non-const, because it changes
*this.
{
char ch;
istr>>this.name;
this is a pointer, so you need this->name to access the name member.
istr>>ch;
istr>>this.degree;
return istr;
}
<snip>
Could anybody here help ?
Thanks and best regards,
Sam
Bart v Ingen Schenau