-5

I want to make three[0]='p'; work in the code below. I think I have to make an operator overloading for that but I don't know how to do. What I want to get is to change first index of "Lottery winner!" to 'p'. (To get "pottery winner!").

#include<iostream>
#include<cstring>
using namespace std;

class str
{
    char* a;
 public:
    str(char *aa=""){
    this->a = new char[strlen(aa)+1];
    strcpy(a,aa);
}

~str(){
    delete a;
}

friend ostream& operator<<(ostream &out, str &aa);
friend istream& operator>>(istream &in, str &aa);

};
ostream& operator<<(ostream &out, str &aa){ 
    out<<aa.a;
    return out;
}

istream& operator>>(istream &in, str &aa){
    in>>aa.a;
    return in;
}

void main(){
  str three("Lottery winner!");
  three[0]='p';
  cout<<three<<endl;
}
ria
  • 5
  • 3
  • 3
    Possible duplicate of [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user0042 Oct 11 '17 at 07:10

3 Answers3

1

This is the general signature of the operator[]:

T& operator[](any_type);

In your context it would look like this:

struct str {

    ...

    char& operator[](std::size_t pos) {
        return a[pos];
    }

};
OutOfBound
  • 1,914
  • 14
  • 31
0
class str
{
    // ...
public:
    // ...
    char& operator[] (int x) 
    {
      // add array out-of-bounds check here if you like to ...
      return a[x];
    }
}
0
operator char*() 
{
    return a; 
}

Could also work

unknown
  • 368
  • 4
  • 12