class rational
{
public:
void AddRational(const rational &,const rational &);
private:
int num,denom;
};
Is it legal in C++???
can I have arguments of the same class type in a member function of the class....like this
Plz help me out !!!!!!
[edited by - nouman on May 6, 2002 6:21:40 AM]
ok but when I compile it I get errors
heres the complete class declaration
and the function definitions are
when I compile this file in MSVC++ I get error
error C2662: ''GetNum'' : cannot convert ''this'' pointer from ''const class rational'' to ''class rational &''
wat is this????
heres the complete class declaration
class rational{public: rational(int=1,int=1); void SetRational(int,int); int GetNum(void); int GetDenom(void); void DisplayRational(void); void AddRational(const rational &,const rational &);private: void Reduce(void); int gcd(const int, const int); int num, denom;};
and the function definitions are
# include<iostream.h># include"rational.h"rational::rational(int n,int d){ SetRational(n,d);}void rational::SetRational(int n,int d){ num=n; denom=(d==0)?1:d; Reduce();}int rational::GetNum(void){ return num;}int rational::GetDenom(void){ return denom;}void rational::DisplayRational(void){ cout<<num<<"/"<<denom;}void rational::AddRational(const rational &tR1, const rational &tR2){ num=tR1.GetNum(); denom=tR2.GetDenom();}void rational::Reduce(void){ int divisor; divisor=gcd(num,denom); num=num/divisor; denom=denom/divisor;} int rational::gcd(const int x, const int y){ if (y==0) return x; return gcd(y,x%y);}
when I compile this file in MSVC++ I get error
error C2662: ''GetNum'' : cannot convert ''this'' pointer from ''const class rational'' to ''class rational &''
wat is this????
The compiler is complaining that it cannot convert from a const rational to a non-const rational. That means that somewhere you are treating a const rational as if it were not constant.
In this case, you call GetNum and GetDenom on the parameters to your function. These two methods are not const, so the compiler assumes they modify the object they are called on (whether or not they do). You need to declare and define them like this:
Doing this informs the compiler that you are never going to change the object which you call the method on, allowing you to use it on a const object.
[edited by - Krunk on May 6, 2002 7:14:09 AM]
In this case, you call GetNum and GetDenom on the parameters to your function. These two methods are not const, so the compiler assumes they modify the object they are called on (whether or not they do). You need to declare and define them like this:
class rational{ ... int GetNum(void) const; ...};int rational::GetNum(void) const {return num;}
Doing this informs the compiler that you are never going to change the object which you call the method on, allowing you to use it on a const object.
[edited by - Krunk on May 6, 2002 7:14:09 AM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement