3

我正在编写一个名为 的类Word,它处理 ac 字符串并重载 <, >, <=,>=运算符。

word.h

friend bool operator<(const Word &a, const Word &b);

word.cc

bool operator<(const Word &a, const Word &b) {
  if(a == NULL && b == NULL)
    return false;

  if(a == NULL)
    return true;

  if(b == NULL)
    return false;

  return strcmp(a.wd, b.wd) < 0;  //wd is a valid c string, EDIT: changed to strcmp
}

main

char* temp = NULL;     //EDIT: i was mistaken, temp is a char pointer
Word a("blah");    //a.wd = [b,l,a,h]
cout << (temp<a);

operator<main. 我可以通过写来纠正问题

cout << (a>temp);

类似的operator>定义并且我没有收到任何错误,但我的任务需要(temp < a)工作,所以这是我寻求帮助的地方。

编辑:我第一次犯了一个错误,我说 temp 是 type Word,但它实际上是 type char*。所以我假设编译器Word使用我的一个构造函数将 temp 转换为 a 。我不知道它会使用哪个,以及为什么这会起作用,因为第一个参数不是Word.

这是我认为用于使用的构造Word函数temp

Word::Word(char* c, char* delimeters="\n") {
  char *temporary = "\0";
  if(c == NULL)
    c = temporary;
  check(stoppers!=NULL, "(Word(char*,char*))NULL pointer"); // exits the program if the expression is false
  if(strlen(c) == 0)
    size = DEFAULT_SIZE;  //10
  else
    size = strlen(c) + 1 + DEFAULT_SIZE;
  wd = new char[size];
  check(wd!=NULL, "Word(char*,char*))heap overflow");
  delimiters = new char[strlen(stoppers) + 1];      // EDIT: changed to []
  check(delimiters!=NULL,"Word(char*,char*))heap overflow");
  strcpy(wd,c);
  strcpy(delimiters,stoppers);
  count = strlen(wd);
}

wd是类型char*

感谢您查看这个大问题并提供帮助。让我知道您是否需要更多代码来查看

4

2 回答 2

1

I'm almost positive you did not mean to construct a char on the heap with an initial value of some integer based on the size of stoppers:

delimiters = new char(strlen(stoppers) + 1); // Should use [] not ()

Also you are using C++ and I would never tell you what to do, but please, unless you know exactly that there is no danger, do not use strcpy. For exactly this reason.

It is a blind copy of strings, and when the destination does not have enough space (as is the case from your typo-ed allocation), things go BAD.

EDIT:

I also see in your overload of operator< that you use

a.wd < b.wd

and claim that .wds are valid C strings. If that is the case, you cannot apply a simple < operator to them and must use strcmp, strncmp or some other full compare function

于 2012-10-25T16:48:07.793 回答
0

删除构造函数的其他部分:

Word::Word(char* c, char* delimeters=NULL) {
    check(stoppers!=NULL, "(Word(char*,char*))NULL pointer");  //exits the program if the expression is false
    delimiters = new char[strlen(stoppers) + 1];
    check(delimiters!=NULL,"Word(char*,char*))heap overflow");
    strcpy(delimiters,stoppers);
}

您正在分配和复制到输入参数 ( delimiters) 而不是成员变量 ( stoppers)。因此,当您调用时:

delimiters = new char[strlen(stoppers) + 1];

在这里,stoppers == NULL(从check调用中推断)所以strlen(NULL)崩溃了。

此外,在:

bool operator<(const Word &a, const Word &b)

您检查诸如a == NULL. 这不是必需的,因为a它们b是引用,因此对象是非空的。

如果wd可以为空,则需要将这些更改为检查a.wdb.wd

于 2012-10-25T17:01:23.707 回答