简体   繁体   English

如何为对象超载cout?

[英]How do I overload cout for my object?

I have a this struct: 我有一个这个结构:

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

My BigInt class has private member variables: Bigint *head and Bigint *tail. 我的BigInt类具有私有成员变量:Bigint * head和Bigint * tail。

What I am trying to do is implement a BigInt datatype. 我正在尝试执行的是实现BigInt数据类型。 My struct is a doubly linked list with each node containing a digit of a number. 我的结构是一个双向链接列表,每个节点包含一个数字位。 The number it should represent is the number you would get from the linked list if you read each character left to right. 它应该代表的数字是,如果您从左到右阅读每个字符,将从链接列表中获得的数字。

This is my constructor: 这是我的构造函数:

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;

}

This is my attempt at an operator<< overloader: 这是我对运算符<<重载程序的尝试:

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

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

  return  stream << num; 
}

This is my error: 这是我的错误:

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) 抛出'std :: bad_alloc'what()实例后调用终止终止:std :: bad_alloc中止(核心转储)

The problem is that in your while loop the ptr variable never contains NULL . 问题是在您的while循环中, ptr变量从不包含NULL This causes an endless loop that exhausts all of your memory while it builds the string. 这将导致一个无穷循环,在构建字符串时会耗尽所有内存。 To fix this you need to advance ptr to the next linked element. 要解决此问题,您需要将ptr前进到下一个链接的元素。 The second problem is that you are storing values 0 through 9 in digit instead of actual their respective characters representations. 第二个问题是您将digit存储 0到9,而不是实际存储它们各自的字符表示形式。 You need to adjust the value when you append it to the string, like so. 将其附加到字符串时,需要进行调整,就像这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM