May 10, 2013 at 3:43am UTC
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
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
class frac{
friend void print(frac& o) const ;
double num;
double denom;
public :
void set(double ,double );
frac operator + (frac &) const ;
void print();
};
void frac::set(double n, double d){
for (int i = 2; i<=n && i<=d; i++){
if (fmod(n,i) == 0 && fmod(d,i) == 0){
n/=i;
d/=i;
i = 2;
}
}
num = n, denom = d;
}
frac frac::operator + (frac &o) const {
frac a = *this ;
a.num = a.num*o.denom + o.num*a.denom;
a.denom = a.denom*o.denom;
return a;
}
void print(frac& o) const {
cout << o.num << '/' << o.denom << endl;
}
int main(){
frac o1, o2, o3;
o1.set(10,5);
o2.set(4,2);
o3 = o1+o2;
print(o3);//**
return 0;
}
D:\VC 6.0\xnx\x.cpp(9) : error C2270: 'print' : modifiers not allowed on nonmember functions
D:\VC 6.0\xnx\x.cpp(36) : error C2270: 'print' : modifiers not allowed on nonmember functions
Last edited on May 10, 2013 at 4:04am UTC
May 10, 2013 at 4:52am UTC
print is not a member function so it cannot be const.
May 10, 2013 at 4:53am UTC
Can a friend function never be const?
May 10, 2013 at 5:03am UTC
The const after the declaration is applied to the implicit this parameter. Friend functions will have no implicit this parameter as they aren't member functions.
May 10, 2013 at 5:04am UTC
Thanks a lot Cire and Firedraco. I love you all!