Hi all, I've looked through £100's worth of text books and all the code I can find but I jsut can't work out how to be able to make a comparison between two class variables, i.e.
if ( a_class A = a_class B ) { return 1; }
I'm trying to apply this concept to compare dates in a custom date of birth class:
#ifndef DOB_H
#define DOB_H
#include <iostream>
// Date of birth class
class dob {
protected:
int _d, _m, _y;
public:
dob(); // Default constructor
dob(int d, int m, int y); // General constructor
int d() const {return _d;} // Return day of birth
int m() const {return _m;} // Return month of birth
int y() const {return _y;} // Return year of birth
// CANT GET THIS BIT TO WORK
//dob operator=(const dob &x); // operates on x
~dob(); // Destructor
};
// Output date of birth for intuitive display to user
std::ostream& operator<< (std::ostream& os, const dob& t);
#endif
// Function file for the date of birth class... __ ...inherited by the ftree class.
#include "dob.h"
usingnamespace std;
// Default constructor - set date, month and year to zero
dob::dob(): _d(0), _m(0), _y(0) {}
// General constructor
dob::dob(int d, int m, int y): _d(d), _m(m), _y(y) {}
// Assignment operator
//dob::dob operator=(const dob &x); // operates on x
// _d(d) = _d(x);
// _m(m) = _m(x);
// _y(y) = _y(x);
// Display date of birth in dd/mm/yy format for output
std::ostream& operator<< (std::ostream& os, const dob& t) {
os << t.d() << '/' << t.m() << '/' << t.y();
return os;
}
// Define destructor
dob::~dob() {}
It seems like such a simple concept in my head but I cant get the code to reflect that!
Sorry for the trouble, any help would be greatly appreciated!
Thanks for your reply! Okay... I've spent ages messing about with this but I jsut can't get it to work, there must be 20 errors or so when I run my = operator. I've read both those sites but their examples are quite different from mine and I'm unable to translate them to my code.
Do you want assignment (operator=) or comparison (operator==)?
In your above code, you just need to remove the asterisks from *x.
However, you should also make your x parameter a const reference
and you also have an extraneous "dob":
dob& dob::operator=( dob const& x ) { ... }
If you want comparison, operator== is very similar in syntax: