可能重复:
运算符重载
我想要做的是重载一个使用多项式添加常数的运算符。这是类定义。
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;
};
因为我们无法访问内置类的定义来添加我们想要的操作符作为成员函数。我们别无选择,只能使用非成员函数。但是当我尝试这样做时,会出现一个错误,即“..'operator +' must have at least one form parameter of class type..”
friend polynomial* const operator+(double,polynomial*);
但是,当我尝试传递一个对象而不是它的指针时,另一个问题是,当它从其他函数返回时,它会自动调用析构函数并擦除对象内部指针指向的所有数据。
polynomial* const operator+(double constant,polynomial p)
{
-> return p+constant;
}
- p {degree=3 polyNum=0x00de8188 {1.0000000000000000} } 多项式
polynomial* const operator+(double constant,polynomial p)
{
return p+constant;
->
}
- p {degree=3 polyNum=0x00de8188 {-2.6569842580370804e+303} } 多项式