输出操作员没有产生预期的结果
我正在实施一个多项式的私人成员,该私人成员的系数和代表最高学位的INT列表组成。构造函数接收代表多项式系数的向量。这是我对构造函数和输出运算符的实现。
#include <iostream>
#include <vector>
using namespace std;
struct Node{
Node(int data = 0, Node* next = nullptr) : data(data), next(next) {}
int data;
Node* next;
};
class Polynomial{
friend ostream& operator<<(ostream& os, const Polynomial& p);
public:
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
private:
Node* co;
int degree;
};
ostream& operator<<(ostream& os, const Polynomial& p){
Node* temp = p.co;
int degree = p.degree;
while(temp != nullptr){
if(degree == 1){
os << temp->data << "x" << " ";
}else if(degree == 0){
os << temp->data;
}else{
os << temp->data << "x^" << degree << " ";
}
degree--;
temp = temp->next;
}
return os;
}
当我尝试测试代码时,输出为686588744,我认为这是指内存中的位置,而不是17的预期结果。
int main(){
Polynomial p1({17});
cout << p1;
}
有人可以指出我在代码中犯了一个错误吗?
I am implementing a class Polynomial with private members consisting of a singly linked list for its coefficient and an int representing the highest degree. The constructor takes in a vector which represents the coefficients in the polynomial. This is my implementation of the constructor and the output operator.
#include <iostream>
#include <vector>
using namespace std;
struct Node{
Node(int data = 0, Node* next = nullptr) : data(data), next(next) {}
int data;
Node* next;
};
class Polynomial{
friend ostream& operator<<(ostream& os, const Polynomial& p);
public:
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
private:
Node* co;
int degree;
};
ostream& operator<<(ostream& os, const Polynomial& p){
Node* temp = p.co;
int degree = p.degree;
while(temp != nullptr){
if(degree == 1){
os << temp->data << "x" << " ";
}else if(degree == 0){
os << temp->data;
}else{
os << temp->data << "x^" << degree << " ";
}
degree--;
temp = temp->next;
}
return os;
}
When I try to test my code the output was 686588744, which I assume refers to a place in memory, rather than the expected outcome of 17.
int main(){
Polynomial p1({17});
cout << p1;
}
Could anyone point out where I made a mistake in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该构造函数
无效。实际上,它没有构建列表。相反,它会产生许多内存泄漏。
例如,首先分配了一个节点,并将其地址分配给指针
temp
,然后将指针与存储在数据成员temp- temp-&gt; Next
中的值重新分配。那是一个无效的指针。因此,分配节点的地址丢失了。此外,指针
co </code>是非初始化的。
您可以将其重写,例如以下方式
This constructor
is invalid. Actually it does not build a list. Instead it produces numerous memory leaks.
For example at first a node was allocated and its address was assigned to the pointer
temp
and then the pointer was reassigned with the value stored in the data membertemp->next
that is a null pointer. So the address of the allocated node was lost.And moreover the pointer
co
is leaved uninitialized.You can rewrite it for example the following way