Line 12 and 13 I am defining the constructor. Line 13 is initializing the private variables in the class when the constructor is created.
It is [b]almost[b] identical to
1 2 3 4 5 6 7
|
Fraction::Fraction( int numerator, int denominator )
{
this->numerator = numerator;
this->denominator = denominator;
//this is pointing to the private variables. if you dont want to use rename the param
//and do numerator = new_param;
}
|
Except my version initializes using an initialization list and the second example just assigns values to them. The initializer list is the c++11 version.
Line 15 I am overloading the '+' operator so you can do object1 + object 2 ( line 36 in my code )
You can overload most of the operators a few examples: + , - , * , / , % , << , >> , =
Line 27 is another overload but this time I am overloading operator << for the output stream so you can output the object using cout ( line 36 ).
Friend is a keyword in classes that lets a function outside of the class access all of its private variables.
Const is a keyword that tells the compiler that a variable is read-only or can not be modified.
Private is a keyword in a class that tells the compiler that only the class object may access them. Other objects / derived classes may not access them.
Check out chapter 8 and 9 here:
http://www.learncpp.com/
And check out these:
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/classes2/
http://www.cplusplus.com/doc/tutorial/inheritance/
Also technically when you do addition you wouldn't want your function to look like that.
Because you call the function using one object so it would be like Obj.add( obj2 )
Also you are adding two fractions then returning an int???
You should return a string or Fraction object ( string so you can output easy I suppose ) You're trying to return a double anyways.
Then you could do something like this
1 2 3 4 5 6
|
Fraction Fraction::Add( Fraction obj2 )
{
obj2.numerator *= denominator;
obj2.numerator += numerator * obj2.denominator;
return( obj2 );
|
Or this
1 2 3 4 5 6 7 8 9
|
std::string Fraction::Add( Fraction obj2 )
{
obj2.numerator *= denominator;
obj2.numerator += numerator * obj2.denominator;
obj2.denominator *= denominator;
std::stringstream ss;
ss << obj2.numerator << '/' << obj2.denominator;
return( ss.str() );
}
|
http://ideone.com/cLOjjH