Concactenate string and user defined object by + symbol

Hello!

See at the bottom of the code. I would like to be able to execute that code (in comments) , if possible?

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
40
41
  #include <iostream>
#include <string>

using namespace std;

class Rational {
    int num;
    int den;
public:
    Rational ( int num = 0, int den = 1 ) : num(num), den(den) {};
    ~Rational () = default;
    int getNumerator() const { return num; };
    int getDenominator() const { return den; };
};

Rational operator + ( const Rational & lhs, const Rational & rhs ) {
    return Rational((lhs.getNumerator() * rhs.getDenominator()) + (lhs.getDenominator() * rhs.getNumerator()), lhs.getDenominator() * rhs.getDenominator());
}

std::ostream & operator << (std::ostream & os, const Rational & r) {
     os << r.getNumerator() << '/' << r.getDenominator();
}


int main(){

	    Rational a(7, 2);        // 7/5
	    cout << "a is: " << a << endl;
	    Rational b(5, 3);    // 5/3
	    cout << "b is: " << b << endl;
	    cout << a << " + " << b << " = " << a + b << endl;
	    cout << a << " + " << 7 << " = " << a + 7 << endl;
	    cout << 7 << " + " << a << " = " << 7 + a << endl;


	    //string message = "The value of the rational number is ";
            //message+= a; //"The value of the rational number is 7/2"
	    //cout << message << endl;                   // help execute..

	return 0;
}
you need a stringstream to do that because you don't have anything in the class that returns the string data version of it, so you have to turn the stream operator to a string. somehow, to use +=, you need a string or something that implicitly converts to a string (char* works, string literals work, etc).

this isn't necessary, of course: you can skip the middle statement and say
cout << message << a;
which is slightly less work done and same end result.
Last edited on
Topic archived. No new replies allowed.