【问题标题】:overload index operator not working in c++重载索引运算符在 C++ 中不起作用
【发布时间】: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 数组是中间痛苦位的一部分。

标签: c++ operator-overloading


【解决方案1】:

std::strcpy:

char* strcpy( char* dest, const char* src );

将src指向的字符串,包括空终止符,复制到dest指向的第一个元素的字符数组中。

如果 dest 数组不够大,则行为未定义。如果字符串重叠,则行为未定义。

没有明确提及,但是当dest 不是指向字符数组的指针时,您也有未定义的行为。在您的代码中,ans 未初始化。

【讨论】:

  • 我明白你的意思,我这样做了,它已经对我有用了。由于要求仅使用 char*,因此我不能使用字符串
  • @johnbyro 然后忘记答案的最后一部分。看来你没看懂第一部分。在您的代码中,ans 不是字符数组的指针,但strcpy 期望指向字符数组的指针能够正常工作。它正在尝试使用未初始化的 ans 并且无法对此做任何有用的操作
  • @johnbyro 换句话说:您不能仅通过使用 char * ans; 来使方法正确。你需要分配一个字符数组
【解决方案2】:

为了重载 [] 运算符,我们必须将内存分配给指针。然后我们可以分配错误字符串或所需的输出字符串

char* Quotes :: operator[](int n) {
  char* ans = new char[ROWS];
  if(n >= lineCount || n < 0) {
    strcpy(ans," Error, not a valid index...\n");
  }
  else
    strcpy(ans,str[n]);
  return ans;
}

同样为了重载 = 运算符,我们必须特别注意数组的情况,因为数组是不可赋值的。 因此,首先我们为当前对象释放空间,然后根据要复制的新对象重新分配空间

void Quotes :: operator= (const Quotes& q) {
  // delete the current object's data
  while(lineCount >= 0){
    delete [] str[lineCount];
    lineCount--;
  }
  // reclaim the space for passed object and copy
  for(int temp_count = 0 ;temp_count < q.lineCount ; temp_count++) {
    this -> str[temp_count] = new char[strlen(q.str[temp_count]) + 1];
    strcpy(this-> str[temp_count],q.str[temp_count]);
  }
  // if there is no data in other object , simply set lineCount to -1
  this -> lineCount = q.lineCount;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 2021-05-22
    • 2013-06-17
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多