对于项目,我试图建立一个链接列表对象,以便可以使用显式值构造函数对其进行初始化。我希望它看起来像这样:

WORD you("you");//where the object you's linked list now contains y o u;


但是当我打印出对象时,我看到的只是这个符号“ =“
当我打印出您的长度时,我会得到-858993459

这是我的显式值构造函数,有人可以告诉我我在做什么错吗?

WORD::WORD(string s)
{
front = 0;
int i = 0;
int len = s.length();

if(front == 0)
{
    front = new alpha_numeric;
    alpha_numeric *p = front;

    while(s[i] <= len)
    {
        p -> symbol = s[i];
        p -> next = new alpha_numeric;
        p = p -> next;
        p -> symbol = s[i++];
    }
    p -> next = 0;
}
}


这是类声明文件(如果有帮助的话)

#include <iostream>
#include <string>

using namespace std;
#pragma once

class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};

class WORD
{
public:
WORD(); //front of list initially set to Null
WORD(const WORD& other);
WORD(string s); //***EXPLICIT VALUE CONSTRUCTOR
bool IsEmpty(); //done
int Length();
void Add(char); //done
//void Insert(WORD bword, int position);
//void operator=(char *s);

friend ostream & operator<<(ostream & out, const WORD& w);//done

private:
alpha_numeric *front; //points to the front node of a list
int length;
};

最佳答案

您无需设置长度,所以这就是垃圾的原因。正如luthien256 ahd LihO指出的那样,您的while循环也是错误的,并且if(front == 0)测试没有任何意义。

最后,不需要p -> symbol = s[i++];。只是增加我。

尝试这个:

class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};

class WORD
{
public:
WORD(); //front of list initially set to Null
WORD(const WORD& other);
WORD(string s); //***EXPLICIT VALUE CONSTRUCTOR
bool IsEmpty(); //done
int Length() { return length; }
alpha_numeric *Front() { return front; }
void Add(char); //done
//void Insert(WORD bword, int position);
//void operator=(char *s);

friend ostream & operator<<(ostream & out, const WORD& w);//done

private:
alpha_numeric *front; //points to the front node of a list
int length;
};

WORD::WORD(string s)
{
  front = 0;
  int i = 0;
  int len = s.length();
  length = len;
  if (length == 0) {
    front = NULL;
    return;
  }
  front = new alpha_numeric;
  alpha_numeric *p = front;

  while(i < len)
  {
      p -> symbol = s[i];
      if (i != len - 1) {
        p -> next = new alpha_numeric;
        p = p -> next;
      }
      else
        p -> next = NULL;
      ++i;
  }
}


int main() {
  WORD you("you");
  alpha_numeric* front = you.Front();
  while(front != NULL) {
    cout<<(front->symbol)<<endl;
    front = front->next;
  }
  cout<<you.Length()<<endl;
  return 0;
}

08-16 11:46