- #1
MathematicalPhysicist
Gold Member
- 4,699
- 372
I have the following code for operations on polynomials in C++, I get plenty of errors which I want to rectify, here's the code:
I get an error with "declaration of 'class <T>'", I get more errors, but first this one, how to fix this?
I just copied this code from a book on solving pdes with c++, I added the math library since I thought that it will include the max and min functions.
Code:
#include<stdio.h>
#include<math.h>
template<class T> class list{
protected:
int number;
T** item;
public:
list(int n=0):number(n), item(n ? new T*[n]:0){
} // constructor
list(int n, const T&t)
: number(n), item(n ? new T*[n] : 0){
for(int i=0; i<number; i++)
item[i] = new T(t);
} // constructor with T argument
list(const list<T>&);
const list<T>& operator=(const list<T>&);
template<class T> class polynomial:public list<T>{
public:
polynomial(int n=0){
number = n;
item = n ? new T*[n] : 0;
for(int i=0; i<n; i++)
item[i] = 0;
} // constructor
polynomial(int n, const T&a){
number = n;
item = n ? new T*[n] : 0;
for(int i=0; i<n; i++)
item[i] = new T(a);
} // constructor with ’T’ argument
template<class T>
const polynomial<T>&
operator+=(polynomial<T>& p, const polynomial<T>&q){
if(p.size() >= q.size())
for(int i=0; i<q.size(); i++)
p(i) += q[i];
else{
polynomial<T> keepQ = q;
p = keepQ += p;
}
return p;
} // add polynomial
template<class T>
const polynomial<T>
operator+(const polynomial<T>& p,
const polynomial<T>&q){
polynomial<T> keep = p;
return keep += q;
} // add two polynomials
template<class T>
const polynomial<T>&
operator*=(polynomial<T>& p, const T&a){
for(int i=0; i<p.size(); i++)
p(i) *= a;
return p;
} // multiplication by scalar
template<class T>
const polynomial<T>
operator*(const T&a, const polynomial<T>&p){
polynomial<T> keep = p;
return keep *= a;
} // scalar times polynomial
template<class T>
polynomial<T>
operator*(const polynomial<T>&p,const polynomial<T>&q){
polynomial<T> result(p.degree()+q.degree()+1,0);
for(int i=0; i<result.size(); i++)
for(int j=max(0,i-q.degree());
j<=min(i,p.degree()); j++){
if(j == max(0,i-q.degree()))
result(i) = p[j] * q[i-j];
else
result(i) += p[j] * q[i-j];
}
return result;
} // multiply two polynomials
template<class T>
polynomial<T>&
operator*=(polynomial<T>&p, const polynomial<T>&q){
return p = p * q;
} // multiply by polynomial
int main(){
polynomial<double> p(3,1);
print(p * p);
return 0;
}
I just copied this code from a book on solving pdes with c++, I added the math library since I thought that it will include the max and min functions.