# Visual C++ friend function problem

• 03-22-2004
cs378
Visual C++ friend function problem
i tired to use friend for << operator in Visual c++ but it gives me error that i cant access private variable in the class

can anyone help me how to fix this problem

thx u

here is examples of a simple program that is perfectly legal but n0t in visual c++

Code:

// Fraction.cpp
#include <iostream>
#include <cmath>
#include "Fraction.h"
using namespace std;

Fraction::Fraction() : numerator(0), denominator(1) { }

Fraction::Fraction(int n) : numerator(n), denominator(1) { }

Fraction::Fraction(int n, int d) {
if (0 == d) {
cout << "Illegal value for denominator" << endl;
exit(1);
}

numerator = n;
denominator = d;
reduce();
}

void Fraction::reduce() {
int g = gcd(abs(numerator), abs(denominator));
numerator /= g;
denominator /= g;
}

//ERROR in Visual C++ here, Can't access private variable

ostream& operator<< (ostream& output, const Fraction& f1) {
if (((f1.numerator < 0) || (f1.denominator < 0))
&& !((f1.numerator < 0) && (f1.denominator < 0)))
output << " - ";
output << abs(f1.numerator) << " / " << abs(f1.denominator);
return output;
}

istream& operator>> (istream& input, Fraction& f1) {
int n, d;
char ch;
input >> n >> ch >> d;
if (ch != '/') {
cout << "Fraction format error." << endl;
exit(1);
}
if (0 == d) {
cout << "Illegal value for denominator." << endl;
exit(1);
}
f1.numerator = n;
f1.denominator = d;

return input;
}

// Helper funtion which returns gcd of two numbers
int Fraction::gcd(int x, int y) {
if (x % y == 0)
return y;
return gcd(y, x % y);
}

Code:

// Fraction.h
#ifndef FRACTION_H
#define FRACTION_H

class Fraction {
public:
Fraction();
Fraction(int);
Fraction(int, int);
double getFraction() const {return ((double) numerator / denominator);}
int getNumerator() const {return numerator;}
int getDenominator() const {return denominator;}
friend ostream& operator<< (ostream&, const Fraction&);
friend istream& operator>> (istream&, Fraction&);

private:
void reduce();
static int gcd(int, int);
int numerator, denominator;
};

#endif

• 03-22-2004
cs378
BTW, im using Visual C++ 6.0
• 03-22-2004
jlou
You failed to mention the other errors that came before that one. The problem is that the compiler doesn't recognize ostream and istream in the header file. You must #include <iostream> and add std:: to the stream names.

This is almost always a good place to start when sorting through lots of errors:
Code:

fraction.h(13) : error C2061: syntax error : identifier 'ostream'
• 03-23-2004
cs378
oh i c

stupid me

how could i forgot abt