我试图将+运算符重载为成员函数,以便我可以将两个多项式对象(链接列表)一起添加,并且我不断收到错误消息conversion from 'Polynomial*' to non-scalar type 'std::shared_ptr<Polynomial>' requested
我不明白是什么导致这个?我已经为我的Term对象声明了两个共享指针,所以我不明白为什么我不能为多项式对象做这个?
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&amp; 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++;
}
}
答案 0 :(得分:7)
在这里,您要求从Polynomial*
到std::shared_ptr
进行隐式转换:
shared_ptr<Polynomial> result = new Polynomial();
但由于std::shared_ptr
构造函数为explicit
,因此无法进行转换。
您需要将Polynomial*
明确传递给std::shared_ptr
构造函数:
std::shared_ptr<Polynomial> result(new Polynomial);
或使用等效的新统一初始化语法:
std::shared_ptr<Polynomial> result{new Polynomial};