Overloaded Operator function in main
I don't exactly know how to test my
==
friend function in my main.
Any help would be appreciated.
Here is my .h file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include<iostream>
using namespace std;
class Car{
public:
Car();
Car(int yer, string mke);
int getYear();
string getMake();
int getSpeed();
int accelerate();
int brake();
friend bool operator==(Car car1, Car car2);
friend istream& operator>>(istream& in, Car& c);
friend ostream& operator<<(ostream& out, const Car& c);
private:
int year;
string make;
int speed;
};
|
Here is my source.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include<iostream>
#include"/home/dylan/Desktop/test/car.h"
using namespace std;
Car::Car(){
year=0;
make="0";
speed=0;
}
Car::Car(int yer, string mke){
year=yer;
make=mke;
speed=0;
}
int Car::getYear(){return year;};
string Car::getMake(){return make;};
int Car::getSpeed(){return speed;};
int Car::accelerate(){
speed+=5;
}
int Car::brake(){
speed-=5;
}
bool operator==(Car car1, Car car2){
if((car1.year==car2.year)&&(car1.make==car2.make)){
return true;
}
else{
return false;
}
}
istream& operator>>(istream& in, Car& c){
in>>c.year>>c.make>>c.speed;
return in;
}
ostream& operator<<(ostream& out, const Car& c){
out<<c.year<<" "<<c.make<<" "<<c.speed;
return out;
}
|
Here is the main.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include<iostream>
#include"/home/dylan/Desktop/test/car.h"
using namespace std;
int main(){
Car objCar, car1, car2;
Car consCar(0, "0");
for(int i=0;i<5;i++){
objCar.accelerate();
cout<<objCar.getSpeed()<<endl;
}
cout<<endl;
for(int j=0;j<5;j++){
objCar.brake();
cout<<objCar.getSpeed()<<endl;
}
cin>>car1;
cin>>car2;
cout<<car1<<endl;
cout<<car2<<endl;
return 0;
}
|
Last edited on
It'd look like this:
1 2 3 4 5 6 7 8 9 10
|
cin>>car1;
cin>>car2;
// ->
if(car1 == car2)
cout<<"cars are equal"<<endl;
else
cout<<"cars are not equal"<<endl;
// <-
cout<<car1<<endl;
cout<<car2<<endl;
|
You should tweak your comparison function to it uses const refs, to avoid unnecessary copying.
bool operator==(const Car& car1, const Car& car2);
Also, as operator&& and operator== both return a bool value (true or false), you can simplify the code to
1 2 3
|
bool operator==(const Car& car1, const Car& car2){
return ((car1.year==car2.year)&&(car1.make==car2.make));
}
|
Andy
Thank you for everyones input it helped alot Cheers.
Topic archived. No new replies allowed.