I'm working with a simple object "Fraction." It holds a numerator and a denominator. I've also make a member function called .print() that simply prints the fraction.
When I try to use the .print() on a member of a dynamic array I get an error when I try to compile.
Isn't a pointer to an object usable as an object and can use the dot (.) modifier to call member functions?
This is the error I get when I try to compile.
1 2 3
$g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:66: error: request for member ‘print’ in ‘(frPtr + 16u)’, which is of non-class type ‘Fraction*’
// playing with pointers and objects
#include <iostream>
usingnamespace std;
class Fraction {
public:
Fraction( void ) { // default constructor
num = 1;
denom = 1;
}
Fraction( int arg1, int arg2 ) { // set
num = arg1;
denom = arg2;
}
~Fraction( void ) { // deconstructor
}
void print( void ); // prints the fraction
private:
int num;
int denom;
}; // end Fraction class
void loadFractions( Fraction*, int );
// loads the dynamic array with fractions
int main( void ) {
int size;
cout << "How many fractions would you like to work with : ";
cin >> size;
// setting up a dynamic array of fractions.
Fraction* frPtr = new Fraction[ size ];
loadFractions( frPtr, size );
// testing .print() on a simple fraction
Fraction x( 2, 3 );
cout << "Value of x.print() " << endl;
x.print();
// setting up a normal array of Fractions.
Fraction frArray[ 2 ] = { Fraction( 1, 2 ), Fraction( 2, 3 ) };
// this works!
cout << "Value of frArray[ 0 ].print " << endl;
frArray[ 0 ].print();
// assuming I have a dynamic array of at lest size 3
// attempting to use .print() to print the 2nd member of
// frPtr. Doesn't work.
*( frPtr + 2 ).print();
return 0;
}
void loadFractions( Fraction* arg, int size ) {
int inputNum;
int inputDenom;
for ( int i = 0; i < size; i++ ) {
cout << "Element [ " << i << " ] "
<< "\n num : ";
cin >> inputNum;
cout << " Denom : ";
cin >> inputDenom;
*( arg + i ) = Fraction( inputNum, inputDenom );
}
return;
}
void Fraction::print( void ) {
cout << "( " << num << " / " << denom << " ) " << endl;
return;
}
What I'd like to be able to is send the dynamic array though a for loop and print them all out.
You should consider using the -> operator when working with pointers, rather than the . operator. It makes the intention a little more clear. But I see you are trying to dereference the pointer before using the . operator. That would work, but operator precedence gets in the way. The . operator takes precedence here. The compiler is interpreting this as: