I am trying to overload the + operator as a member function so that I can add two polynomial objects (which are linked lists) together and I keep getting an error message conversion from 'Polynomial*' to non-scalar type 'std::shared_ptr<Polynomial>' requested
I don't understand what is causing this? I have declared two shared pointers for my Term objects so I don't understand why I can't do this for a polynomial object?
Polynomial Polynomial::operator+( const Polynomial &other ) const
{
shared_ptr<Polynomial> result = new Polynomial();
shared_ptr<Polynomial::Term> a = this->head;
shared_ptr<Polynomial::Term> b = other.head;
double sum = 0;
for(a; a != nullptr; a = a->next)
{
for(b; b != nullptr; b = b->next)
{
if(a->exponent == b->exponent)
{
sum = a->coeff + b->coeff;
result->head = shared_ptr<Term>(new Term( sum, a->exponent, result->head ));
cout << "function has found like terms" << endl;
}
else if(a->exponent != b->exponent)
{
result->head = shared_ptr<Term>(new Term( a->coeff, a->exponent, result->head ));
cout << "function is working" << endl;
}
}
}
result;
}
main.cpp
void makePolynomials( shared_ptr [], int &x );
int main()
{
shared_ptr<Polynomial> poly[ 100 ];
int nPolynomials = 0;
makePolynomials( poly, nPolynomials );
makePolynomials( poly, nPolynomials );
for (int j=0; j < nPolynomials; j++)
cout << *(poly[j]);
//shows that the addition operator works
Polynomial c;
c = *(poly[0])+*(poly[1]);
cout << c << endl;
}
void makePolynomials( shared_ptr<Polynomial> poly[], int &nPolynomials )
{
char filename[20];
cout << "Enter the filename: ";
cin >> filename;
ifstream infile;
infile.open( filename );
if (! infile.is_open()) {
cerr << "ERROR: could not open file " << filename << endl;
exit(1);
}
string polynom;
while (getline( infile, polynom ))
{
poly[ nPolynomials ] = shared_ptr<Polynomial>(new Polynomial( polynom ));
nPolynomials++;
}
}
Here you're requesting an implicit conversion from Polynomial*
to std::shared_ptr
:
shared_ptr<Polynomial> result = new Polynomial();
But since the std::shared_ptr
constructor is explicit
, the conversion isn't possible.
You need to pass the Polynomial*
explicitly to the std::shared_ptr
constructor:
std::shared_ptr<Polynomial> result(new Polynomial);
or using the equivalent new uniform initialization syntax:
std::shared_ptr<Polynomial> result{new Polynomial};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With