【发布时间】:2020-11-25 19:35:07
【问题描述】:
# define ROWS 1024
# define COLS 1024
class Quotes {
private:
char *str[ROWS]; // holds data for up to 1024 lines
int lineCount; //count the lines read in array
// method to read file content
void readContent(string fileName);
public:
Quotes(string fileName);
Quotes(const Quotes& q);
// some other method
// this operator overloading not working
char* operator[](int n);
};
/** some other methods definition ***/
Quotes :: Quotes(string fileName) {
lineCount = -1 ; // blank line
readContent(fileName);
}
Quotes :: Quotes(const Quotes& q) {
*this = q;
}
void Quotes :: readContent(string fileName) {
ifstream fp(fileName);
if(!fp.is_open()) {
cout<<"\n file can not be read";
return;
}
// initialise lineCount here as in case file is not read , one should avoid the initialise counter
lineCount = 0;
char temp[COLS];
while(fp.getline(temp,COLS)) {
str[lineCount] = new char[strlen(temp) + 1];
strcpy(str[lineCount], temp);
lineCount++;
}
fp.close();
}
/*
This method returns the string stored at given index if index is valid , otherwise return an error string as provided in the code
*/
char* Quotes :: operator[](int n) {
char* ans;
cout<<"\n in method with :"<<n; //even this line is not executing while debugging it
if(n >= lineCount || n < 0) {
strcpy(ans," Error, not a valid index...");
}
else
strcpy(ans,str[n]);
return ans;
}
在这里,我想重载索引运算符以获取给定索引处的字符串。我完全理解在 C++ 中我们不需要将字符串存储在 char 数组中,我们可以直接使用字符串。 这是在char数组(指针)中存储文件数据的具体需要
重载的方法 [] 不起作用,即使数据存在,它也会显示错误“分段错误”
测试代码
Quotes q("sample.txt");
// method 1
char* res ;
strcpy(res,q[2]);
//method 2
cout<<q[2];
还有重载 = 运算符(赋值)的帮助吗?
【问题讨论】:
-
ans只是一个指向单个字符的指针。您忘记为字符串分配内存(ans甚至没有指向单个char,它没有指向任何地方)。你为什么不使用std::string? -
请给我们更多代码 - 构造函数的实现和尝试使用 operator[] 的代码
-
@idclev463035818 因为,根据 Thomas Wolfe 的说法,“人生来就是为了生存,为了受苦,为了死亡[。]”动态
char数组是中间痛苦位的一部分。