-
operator+ overloading
Hey, I'm trying to overload the assignment operator '+' to add two objects. I need to add throttle sample2 and throttle sample3.
I've tried several things and keep getting errors.
Here is what I am working on...
Code:
//Operator fxn outside class
#include <iostream>
#include <cstdlib>
using namespace std;
class throttle
{
public:
throttle(); //default constructor function
throttle(int size);//other constructor
throttle(throttle ©);//copy constructor
throttle operator+(throttle& temp, throttle& temp2);
int get_pos(){return position;}
int get_max(){return max;}
void shut_off();
void shift(int amount);
double flow() const;
bool is_on() const;
private:
int position;
int max;
};
throttle::throttle()
{
max=1;
position=0;
}
throttle::throttle(int size)
{
max=size;
position=0;
}
throttle::throttle(throttle ©)
{
max=copy.max;
position=copy.position;
}
//operator fxn declaration outside of class
void throttle::shut_off()
{position=0;
}
void throttle::shift(int amount)
{
position += amount;
if(position<0)
position=0;
else if (position>max)
position=max;
}
double throttle::flow()const
{
return position/6.0;
}
bool throttle::is_on() const
{
return (flow()>0);
}
int main()
{
throttle total;
throttle sample(10);
sample.shift(5);
throttle sample2(sample);
throttle sample3(sample);
int user_input;
cout << "I have 2 throttles with 10 positions." << endl;
cout << "Where would you like to set the throttle?" << endl;
cout << "Please type a number 0 to 10: ";
cin >> user_input;
sample2.shut_off();
sample2.shift(user_input);
cout << "Second Throttle." << endl;
cout << "Where would you like to set the throttle?" << endl;
cout << "Please type a number 0 to 10: ";
cin >> user_input;
sample3.shut_off();
sample3.shift(user_input);
while (sample2.is_on())
{
cout << "The flow for throttle one is now " << sample2.flow() << endl;
sample2.shift(-1);
}
cout << "The flow is now off" << endl;
while (sample3.is_on())
{
cout << "The flow for throttle two is now " << sample3.flow() << endl;
sample3.shift(-1);
}
cout << "The flow is not off" << endl;
//adding two throttles
return EXIT_SUCCESS;
}
-
operator+(throttle& temp, throttle& temp2); is not a member function.
Code:
class throttle {
...
throttle(throttle&);//copy constructor
friend throttle operator+(const throttle& temp,const throttle& temp2);
...
};
...
throttle operator+(const throttle& temp,const throttle& temp2)
{
//Your Implementation
}
...
throttle::throttle(throttle & copy)
{
max=copy.max;
position=copy.position;
}