c++ - 如何为我的对象重载 cout?

标签 c++ linked-list operator-overloading

我有一个这样的结构:

struct DigitNode{
  char digit;
  DigitNode *prev;
  DigitNode *next; 
};

我的 BigInt 类有私有(private)成员变量:Bigint *head 和 Bigint *tail。

我想做的是实现一个 BigInt 数据类型。我的结构是一个双向链表,每个节点都包含一个数字。如果您从左到右阅读每个字符,它应该代表的数字是您将从链表中获得的数字。

这是我的构造函数:

BigInt::BigInt(const string &numIn) throw(BigException)
{  

  DigitNode *ptr = new DigitNode;
  DigitNode *temp;
  ptr->prev = NULL;
  if (numIn[0] == '-' || numIn[0] == '+') ptr->digit = numIn[0];
  else ptr->digit = numIn[0] - '0';
  this->head = ptr;
  for (int i = 1; numIn[i] != '\0'; i++)
    {
      ptr->next = new DigitNode;
      temp = ptr;
      ptr = ptr->next;
      ptr->digit = numIn[i] - '0';
      ptr->prev = temp;
    }
  ptr->next = NULL;
  this->tail = ptr;

}

这是我对运算符<<重载器的尝试:

ostream&  operator<<(ostream & stream, const BigInt & bigint)
{ 

  DigitNode *ptr = bigint.head;
  string num = "";
  while (ptr != NULL)
    {
      num += ptr->digit;
    }

  return  stream << num; 
}

这是我的错误:

在抛出“std::bad_alloc”实例后调用终止 什么():std::bad_alloc 中止(核心转储)

最佳答案

问题是在您的 while 循环中,ptr 变量从不包含 NULL。这会导致无限循环,在构建字符串时耗尽所有内存。要解决此问题,您需要将 ptr 前进到下一个链接元素。第二个问题是您将 0 到 9 存储在 digit 中,而不是实际的它们各自的字符表示形式。将其附加到字符串时需要调整该值,就像这样。

while (ptr != NULL)
{
    num += ptr->digit + '0';
    ptr = ptr->next;
}

关于c++ - 如何为我的对象重载 cout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27364878/

相关文章:

c++ - 运算符重载非成员函数?

c++ - 在 Windows 中,UuidFromString 和 CLSIDFromString 之间有区别吗?

java - 如何使用 Java 创建二叉树最大深度中包含的节点的链表

c++ - 如何摆脱丑陋的记录

C程序不会打印链表中的节点

c++ - 链表的构造函数

c++ - 错误 C2678 : binary '!=' : no operator found

c++ - 涉及全局对象的循环依赖 C++

c++ - 函数调用参数总是一个新对象吗?

c++ - Mac 上的 qt : Form Layout fails to stretch horizontally