G
gobis
Hello everyone,
After I could not overload the << operator as a friend operator in my
template class (yes, it did not have to be a template class, but I was
testing something for the class I was going to teach) , I declared the
operator outside the class definition. This would prevent the operator
from accessing the private elements within the class, so I provided
access to elements of the private vector array thru a public member
function. But then I found that I could not place the const specifier
before the templated class argument in the overloaded operator
definition:
template <class C> ostream& operator << (ostream& os, const
Polynom<C>& p)
{
for(int i=p.GetOrder()+1; i>0; i--)
{
os << p.Coeff(i) << "*x^" << i << " + ";
}
os << p.Coeff(0) << endl;
return os;
}
The compiler (Bloodshed Dev C++) complained that passing a Polynom<int>
or a Polynom<double> instance to the operator would discard qualifiers.
I suppose the compiler wants the array member returned by the
Coeff(int) member function to be const as well, but I could not add the
const specifier in that definition. It did not supress the error
message.
Can anybody see what I am doing wrong?
Relevant code follows:
in the .hpp file:
template <class C> class Polynom
{
/*** Constructors and Destructors ***/
...
/*** Public methods ***/
...
C Coeff(int i);
...
/*** Data members ***/
private:
vector<C> coef;
};
in the .cpp file:
template <class C> C Polynom <C>::Coeff(int i)
{
return coef;
}
My regards,
Hurol Aslan
After I could not overload the << operator as a friend operator in my
template class (yes, it did not have to be a template class, but I was
testing something for the class I was going to teach) , I declared the
operator outside the class definition. This would prevent the operator
from accessing the private elements within the class, so I provided
access to elements of the private vector array thru a public member
function. But then I found that I could not place the const specifier
before the templated class argument in the overloaded operator
definition:
template <class C> ostream& operator << (ostream& os, const
Polynom<C>& p)
{
for(int i=p.GetOrder()+1; i>0; i--)
{
os << p.Coeff(i) << "*x^" << i << " + ";
}
os << p.Coeff(0) << endl;
return os;
}
The compiler (Bloodshed Dev C++) complained that passing a Polynom<int>
or a Polynom<double> instance to the operator would discard qualifiers.
I suppose the compiler wants the array member returned by the
Coeff(int) member function to be const as well, but I could not add the
const specifier in that definition. It did not supress the error
message.
Can anybody see what I am doing wrong?
Relevant code follows:
in the .hpp file:
template <class C> class Polynom
{
/*** Constructors and Destructors ***/
...
/*** Public methods ***/
...
C Coeff(int i);
...
/*** Data members ***/
private:
vector<C> coef;
};
in the .cpp file:
template <class C> C Polynom <C>::Coeff(int i)
{
return coef;
}
My regards,
Hurol Aslan