Reputation: 139
I'm trying to overload the stream operator <<
but it is still just printing the object address instead of the object information like I have in the overload function definition. Here's my code, spent quite some time trying every example I could find on the web, but nothing is working. Please help alleviate some of my stress! Thanks.
Interval.h:
#ifndef INTERVAL_H
#define INTERVAL_H
#include <string>
#include <iostream>
#include <assert.h>
using namespace std;
class Interval {
public:
long start;
long end;
// Constructor
Interval(long, long);
// Deconstructor
// Virtual to make sure that it calls the correct destructor
virtual ~Interval();
bool operator==(const Interval &other) const;
bool operator!=(const Interval &other) const;
bool operator<(const Interval &other) const;
bool operator<=(const Interval &other) const;
bool operator>(const Interval &other) const;
bool operator>=(const Interval &other) const;
friend ostream& operator<<(ostream& os, const Interval &i);
};
#endif
Interval.cpp:
#include "Interval.h"
#include <iostream>
#include <string>
using namespace std;
Interval::Interval(long a, long b){
// Assert that start is less than the end
assert(a < b);
start = a;
end = b;
}
// Deconstructor
Interval::~Interval(){
}
bool Interval::operator==(const Interval &other) const{
// Return true if both start and end are equal to other's
if(start == other.start && end == other.end){
return true;
}else{
return false;
}
}
bool Interval::operator!=(const Interval &other) const{
// Return true(not equal) if either the start or end are different
if(start != other.start || end != other.end){
return true;
}else{
return false;
}
}
bool Interval::operator<=(const Interval &other) const{
// Return true if the start is less than or equal other's start
if(start <= other.start){
return true;
}
}
bool Interval::operator>(const Interval &other) const{
// Return true if the end is greater than other's end
if(end > other.end){
return true;
}
}
bool Interval::operator>=(const Interval &other) const{
// Return true if the end is greater than or equal to other's end
if(end >= other.end){
return true;
}
}
bool Interval::operator<(const Interval &other) const{
// Return true if the start is less than other's
if(start < other.start){
return true;
}
}
ostream& operator<<(ostream& os, const Interval &i){
os << "Interval[" << i.start << ", " << i.end << "]" << endl;
return os;
}
int main(void){
Interval *test = new Interval(10,1000);
cout << test << endl;
cout << "test" << endl;
}
Upvotes: 1
Views: 1236
Reputation: 8143
Interval *test = new Interval(10,1000);
The syntax in C++ to create an object on the stack is
Interval test(10,1000);
Don't use pointers unless you have a good reason to do so.
Upvotes: 1
Reputation: 38800
Interval*
is a pointer. You are simply outputting the address.
Try dereferencing the pointer:
cout << *test << endl;
Or try this:
Interval test(10, 1000); // not a pointer.
cout << test << endl;
Upvotes: 5