operator overloading

Good day pals,

Really need your help, reference and opinion about the next task.

Without using the string library functions, I have to write a method using the overloading operator function which will receive as a parameter an int and return the character which is located on that specific int index.

check the code below pls,
note - (STRLEN)- method which I've written in a specific way and is doing exactly the same as the strlen one from cstring. It can work perfectly with objects as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 char operator[](const int x)
 {
 	int n=this->STRLEN();

 	int index;
 	
 	for(int i=0; i<n; i++)
 	{
 		if(this->str[i]==x) index=i;
	}
	return str[index];
 }

int main()
{
 STR A;
 A="ababcdefg";

[A](6); // I am expecting char"e" to be returned but I am facing a couple of errors.

return 0;
}
Last edited on
Why not simply:

1
2
3
4
5
6
7
8
9
const char& operator[](int x) const
{
	return str[x];
}

char& operator[](int x)
{
	return str[x];
}

@seeplus, many thanks, even though I am facing same compile errors as previous :
[Error] expected identifier before numeric constant
[Error] expected ',' or '...' before numeric constant
In lambda function
[Error] expected '{' before ';' token
Sorry,

 
[A](6); 


should be:

 
A[6];

@seeplus, thanks a lot!!
Topic archived. No new replies allowed.