Possible Duplicate:
Operator overloading
What I want to do is overloading an operator which adds a constant with a polynomial. Here is the class definition.
class polynomial
{
public:
polynomial();// default constructor
polynomial(double*,int);// parameterized constructor
polynomial(polynomial*);// copy constructor
~polynomial();//destructor
polynomial* const operator+(polynomial*);
polynomial* const operator+(double);
friend polynomial* const operator+(double,polynomial);
polynomial* operator-(polynomial*);
polynomial* operator-(const double);
polynomial* operator*(polynomial*);
polynomial* polynomial::operator*(const double);
friend ostream& operator<<(ostream&,polynomial*);
friend double evaluate(polynomial*,double);
friend double* extract(polynomial*);
polynomial* operator =(polynomial*);
int degree;
private:
double* polyNum;
};
Because we can not access into the definition of build-in class to add the operator we want as a member function. We have no choice but a non-member function. But when I am trying to do so, it comes up with an error that "..'operator +' must have at least one formal parameter of class type.."
friend polynomial* const operator+(double,polynomial*);
However, when I try to pass a object instead of the pointer of it, another problem that when it return from other function it will call the destructor automatically and erase all the data pointed by the pointer inside the object.
polynomial* const operator+(double constant,polynomial p)
{
-> return p+constant;
}
- p {degree=3 polyNum=0x00de8188 {1.0000000000000000} } polynomial
polynomial* const operator+(double constant,polynomial p)
{
return p+constant;
->
}
- p {degree=3 polyNum=0x00de8188 {-2.6569842580370804e+303} } polynomial