1

可能重复:
运算符重载

我想要做的是重载一个使用多项式添加常数的运算符。这是类定义。

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} } 多项式
4

2 回答 2

0

You seem to be confused about the need for pointers. (Hint: there is no need for pointers in your class.)

To answer your specific question, your operator+ functions should look like this:

class polynomial {
public:
  polynomial& operator +=(double d) {
     polynum[0] += d; // or whatever
     return *this;
  }
  polynomial& operator+=(const polynomial& p) {
    for( ... ) {
      polynum[i] += p.polynum[i]; // or whatever
    }
    return *this;
  }

  // other stuff goes here, too
  ...
};

polynomial operator+(polynomial p, double d) { return p += d; }

polynomial operator+(double d, polynomial p) { return p += d; }

polynomial operator+(polynomial l, const polynomial& r) { return l += r; }

Typical usage would be:

int main () {
  polynomial p, q, r;
  double d;
  ... fill in p, q, and d ...
  q = p + d;
  r = d + p;
  p = q + r;
}
于 2012-11-28T04:04:26.740 回答
0

我之前唯一的复制构造函数是

polynomial(polynomial*);
// copy constructor work with pointer

它使当我将对象而不是指针作为参数传递给函数时

 polynomial* const operator+(double constant,polynomial p)
{
    return p+constant;
}

局部变量只是简单地从外部变量复制值,包括 p.polynum 的值。结果,有两个指针指向同一个数组。当函数完成并准备返回时,它调用析构函数来销毁局部变量p,这顺便销毁了p.polynum的数组。这就是为什么外部指针指向的数组内的值被擦除的原因。这就是为什么我们需要为包含指针的类创建一个真正的复制构造函数。

解决方案:

添加一个额外的复制构造函数:

polynomial(polynomial*);
// copy constructor2 work with object.
于 2012-11-29T02:13:47.750 回答