【发布时间】:2015-03-17 02:46:15
【问题描述】:
我试图将 + 运算符重载为成员函数,以便我可以将两个多项式对象(它们是链表)加在一起,但我不断收到错误消息 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 &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++;
}
}
【问题讨论】:
-
方法中的最后一行
result;应该做什么? -
@mebob 最后一行,假设返回一个新的链表,该链表希望包含表示新多项式项的节点(通过使用加法运算符添加两个现有多项式来创建) --correction 糟糕,应该是返回结果;
-
@user3341399
result;不返回任何内容。为此,您需要使用return关键字。即便如此,result的类型也不同于方法返回类型。 -
@zenith 我的意思是返回结果;这就是程序崩溃的原因吗,因为我返回的是 shared_ptr 而不是多项式对象?
-
@user3341399 你不能在你声明函数返回其他东西的地方返回
shared_ptr。它甚至不应该编译。
标签: c++ shared-ptr dynamic-memory-allocation