简体   繁体   中英

overload index operator not working in c++

# 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;  
}

Here i want to overload the index operator to get the string at given index. I totally understand that in c++ we are not in need to store strings in char arrays, we can use the strings directly. This is the specific need to store file data in char array(pointer)

The overloaded method [] is not working, it says error "Segmentation fault " even when the data is present

Tested code

Quotes q("sample.txt");

// method 1
char* res ;
strcpy(res,q[2]);


//method 2
cout<<q[2];

Also any help to overload the = operator (assignment)?

std::strcpy :

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

Copies the character string pointed to by src, including the null terminator, to the character array whose first element is pointed to by dest.

The behavior is undefined if the dest array is not large enough. The behavior is undefined if the strings overlap.

It is not mentioned explicitly, but you also have undefined behavior when dest is not a pointer to a character array. In your code ans is not initialized.

For overload the [] operator, we have to allocate the memory to the pointer. then we can assign the error string or the desired output string

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;
}

Also for overloading the = operator, we have to take care in case of arrays specially as arrays are not assignable. Hence first we deallocate the space for current object, then reallocate the space as per the new object to be copied into

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM