My little program compiles, but it prints out giberish?
Okay. . . pointers are driving me bonkers!!! Okay, now that I have that out of my system, the following code compiles, however, it does not print out the correct output. What am I doing wrong?
#ifndef _TERM_H
#define _TERM_H
class Term {
public:
//constructors
Term( Rational &a, const int &b)
{
this->coefficient = a;
this->exponent = b;
}
~Term () {}
//coefficient
Rational getCoefficient()const{
return coefficient;
}
//exponent
int getExponent()const{
return exponent;
}
//print the Term
void print()const {
cout << &Term::coefficient << " x^" << &Term::exponent << endl;
}
private:
Rational coefficient, a;
int exponent, b;
};
#endif
#ifndef _RATIONAL_H
#define _RATIONAL_H
class Rational {
public:
//constructors
Rational( const int &a, c开发者_运维技巧onst int &b){
if (a != 0)
if (b != 0)
this->numerator = a;
this->denominator = b;
}
Rational(){}
~Rational() {}
.....
private:
int a, b, numerator, denominator;
};
#endif
Okay, so when I input values (2/5) for my Rational number and i input 2 for my exponent (I am supposed to get( 2/5 x ^2)) I get 1 X^1. Huh? I am running out of hair to pull out. . .
On this line:
cout << &Term::coefficient << " x^" << &Term::exponent << endl;
you're printing out the ADDRESS of Term::coefficient and Term::exponent (that's what the unary &
operator is in this context).
Try removing the &
s and re-compile/run.
Why is print
//print the Term
void print()const {
cout << &Term::coefficient << " x^" << &Term::exponent << endl;
}
Instead of just
void print() const
{
cout << coefficient << " x^" << exponent << end;
}
?
There are several things that seem odd do me:
There is no need to pass ints by const reference. An int is small enough to be passed by value without an impact on performance. Passing by const reference is useful for big objects.
As others have said, you are printing out the adresses of the member variables instead of their values.
You don't need the member variables a and b.
The if-statements in the Rational constructor only apply to the first assignment, while your indentation suggests it should apply to both. Use { ... } for multiple statements, C++ won't care about your indentation.
If the assignment in the Rational constructor doesn't run, numerator and denominator are unassigned and will have an undefined value. Use an initialization list, to set a default value.
You should consider overloading operator<< for Term and Rational instead of writing a print method. This will also allow for cout << coefficient to work as expected.
Thanks to Steve314 for pointing this out: leading underscores in identifiers are reserved and shouldn't be used, to avoid name clashes. So you shouldn't “#define _TERM_H”. See Steves comment for details.
The basic issue is here: &Term::coefficient << " x^" << &Term::exponent You need to reference the instance of class Term. The Rational object also needs a string conversion method.
精彩评论