【发布时间】:2010-03-08 21:50:48
【问题描述】:
我创建了一个类“Entry”来处理字典条目,但是在我的 main() 中,我创建了 Entry() 并尝试计算 char 类型的公共成员,但我得到了垃圾。当我在调试器中查看监视列表时,我看到了正在设置的值,但是一旦我访问这些值,就会出现垃圾。谁能详细说明我可能遗漏了什么?
#include <iostream>
using namespace std;
class Entry
{
public:
Entry(const char *line);
char *Word;
char *Definition;
};
Entry::Entry(const char *line)
{
char tmp[100];
strcpy(tmp, line);
Word = strtok(tmp, ",") + '\0';
Definition = strtok(0,",") + '\0';
}
int main()
{
Entry *e = new Entry("drink,What you need after a long day's work");
cout << "Word: " << e->Word << endl;
cout << "Def: " << e->Definition << endl;
cout << endl;
delete e;
e = 0;
return 0;
}
【问题讨论】:
-
我很惊讶还没有人提供“不要使用 char*,使用 std::string”的建议。在这里。
-
来自该赋值的说明:“你不能使用 C++ 标准库提供的 std::string 类。对于字符串数据的存储,使用以零结尾的字符数组。”