readFruit.name
NULL
在我尝试将其初始化为 char 数组之前已初始化。我包括size
看看这是否是罪魁祸首,但这正是它应该取决于我的输入。无论长度tempString
是多少,readFruit.name
都会在内存中分配大约 25 个“字符”,它们都是垃圾。为什么它没有被分配一个大小的空间,tempString.length()
我该如何修复它?
相关的 CPP
std::istream & operator>>(std::istream &is, Fruit &readFruit)
{
string tempString;
is >> tempString;
int size = tempString.length();
readFruit.name = new char[tempString.length()];
for(int i = 0; i < (int)tempString.length(); i++)
{
readFruit.name[i] = tempString[i];
}
for(int i =0; i < CODE_LEN; i++)
{
is >> readFruit.code[i];
}
return is;
}
相关H文件(构造函数)
#ifndef _FRUIT_H
#define _FRUIT_H
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
enum { CODE_LEN = 4 };
enum { MAX_NAME_LEN = 30 };
class Fruit
{
private:
char *name;
char code[CODE_LEN];
public:
Fruit(const Fruit &temp);
Fruit(){name = NULL;};
bool operator<(const Fruit& tempFruit);
friend std::ostream & operator<<(std::ostream &os, const Fruit& printFruit);
bool operator==(const Fruit& other){return *name == *other.name;};
bool operator!=(const Fruit& other){return *name != *other.name;};
friend std::istream & operator>>(std::istream& is, Fruit& readFruit);
};
#endif