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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

#include <iostream>
using namespace std;
class Rational
{
public:
Rational(const int n=0, const int d=1) : numer(n), denom(d) {
printf("ctor before reduce: n(%d), d(%d) \n", numer, denom);
reduce();
printf("ctor after reduce: n(%d), d(%d) \n", numer, denom);
}
void display(const char *message = "display()") {
printf("%s  numer(%d) denom(%d)\n", message, numer, denom);
}
//*********************** problem ***********************************
//Rational operator+( const Rational & r2) { //this works
//Rational operator+( Rational & r2) { //compile error *****
//Rational operator+( const Rational r2) { //this works
//Rational operator+( Rational r2) { //this works
Rational operator+( Rational & r2) {
Rational temp;
printf("adding: %d/%d + %d/%d \n", numer, denom, r2.numer, r2.denom);
temp.numer = numer*r2.denom + denom*r2.numer;
temp.denom = denom*r2.denom;
return temp;
}
void reduce() {
printf("can we reduce? numer(%d) denom(%d) \n", numer, denom);
for (int i=0; i<9; i++) {
if ( !(numer % divArray[i]) && !(denom % divArray[i]) ) {
printf("divide numer(%d) and denom(%d) by (%d) \n",
numer, denom, divArray[i]);
numer /= divArray[i];
denom /= divArray[i];
i;
}
}
}
private:
static int divArray[10];
int numer;
int denom;
};
int Rational::divArray[10]={2,3,5,7,11,13,17,19,23,29};
int main()
{
Rational mc1(6,14);
Rational mc2(3,9);
Rational mc3(16, 32);
mc1.display("mc1");
mc2.display("mc2");
mc3.display("mc3 before operator +");
mc3 = mc1 + mc2;
mc3.display("mc3 after operator +");
int intVar1 = 3;
mc3 = intVar1;
//******************** Problem **********************************
//no compile error if define: Rational operator+(Rational r2) {...}
// compile error if define: Rational operator+(Rational & r2) {...}
//error C2664: 'Rational::operator +' : cannot convert parameter 1 from 'int' to 'Rational &'
mc3 = mc1.operator+(intVar1);
mc3.display("mc1 + 3");
cout << "exiting... \n";
return 0;
}
