我想重載一個類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