我想重载一个类Poly的+运算符,以便在main.cpp中我可以一起添加到Poly中。我试图做到这一点的方法是:创建新节点的问题
- 比较左侧expnt与右侧expnt
- 创建保利临时与新发现的值的新节点(在解释评论)
- 然后将新的Poly返回到main.cpp以存储在pList []数组中。
出于某种原因,新的节点将被创建,但指针节点丢失这样的main.cpp无法访问温度。我哪里错了?
// class Poly header file
class Poly {
private:
// DATA MEMBERS
struct Node
{
double coEf;
int expnt;
Node* next;
};
Node* first;
.
.
.
}
// class poly definition file
// Private function
Poly::Node* Poly::get_node(const double num1, const int num2, Node* link)
{
Node *temp;
temp = new Node;
temp -> coEf = num1;
temp -> expnt = num2;
temp -> next = link;
return temp;
}
Poly Poly::operator + (Poly source)
{
Node* p1 = first;
Node* p2 = source.first;
Node* last;
Poly temp;
Node* pt = temp.first;
// If the left side Poly is empty then just return the right side Poly.
if(first==NULL)
{
Poly(source);
}
// If the left side Poly's first exponent is equal to the right side Poly's
// exponent, then create a node for Poly temp with the following values:
// expnt = (because the expnt's are equal it doesn't matter which one) (int)
// coEf = both left side and right side's coEf's added together (double)
// next = NULL (because it's the end of temp's list)
if(p1 -> expnt == p2 -> expnt)
{
pt = get_node(((p1 -> coEf)+(p2 -> coEf)), p1 -> expnt, NULL);
p2 = p2 -> next;
p1 = p1 -> next;
}
if(p1 -> expnt > p2 -> expnt)
{
pt = get_node(p1 -> coEf, p1 -> expnt, NULL);
p1 = p1 -> next;
}
if(p1 -> expnt < p2 -> expnt)
{
pt = get_node(p2 -> coEf, p2 -> expnt, NULL);
p2 = p2 -> next;
}
else
{
pt = get_node(1, 2, NULL);
}
return temp;
}
// main.cpp
// function that calls the class member function operator +(Poly source)
void addPoly()
{
int add1;
int add2;
int add3;
cout << "Enter the name of two polynomials to add them: " << endl;
cin >> add1 >> add2;
cout << "Enter a name for the new added polynomial: " << endl;
cin >> add3;
pList[add3] = pList[add1] + pList[add2];
}
我想你的意思是'Node *&pt = temp.first;',所以每个'pt'的修改都会修改'temp'。 – Jarod42 2014-09-27 16:21:34