operator overloading

I am trying but unsuccessful to write an algorithm which will replace the erase function from string library, calling the method in the main function alike object A(0,5)

2 int parameters which will be the array of the next deleted characters.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void operator()(int x, int y) 
{
	
    while (x != y) {
      this->str[x] =' ';
      x++;
      //if (x==y) break;
    }
  }

int main()
{
string A="Gelendwagen";
A(0,5); //expected output "wagen";

return 0;
}
Last edited on
done :)

1
2
3
4
5
6
7
8
9
10
11
void operator()(int x, int y) 
{
	int n=this->STRLEN(); //STRLEN function works as the strlen from string but with objects as well
	
    	for (int i=x; i<n-x; i++;y++)
    	{
    		this->str[i] =this->str[y];
    		this->str[n]=0;
		}
      
    }
Last edited on
Operator () must be declared as a member function. So to do what you want, you'd have to add it to std::string. Not a good idea. What you could do is derive your own string class from std::string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <iostream>

class MyString : public std::string {
public:
    MyString(const char *cp) : std::string(cp) {};
    void operator()(int x, int y) 
    {
	for (; x != y; ++x) {
	    (*this)[x] =' ';
	}
    }
};

int main()
{
    MyString A="Gelendwagen";
    A(0,5); //expected output "wagen";
    std::cout <<  A << '\n';
    return 0;
}

$ ./foo
     dwagen

Notice that I had to declare the constructor that you use and basically forward the call to std::string's constructor. To make this robust, you'd have to do the same for all the other constructors. I'm no sure if there's a way to do that automatically, but I doubt it.
dhayden, thanks a lot for your explanation, all your suggestions were implemented but I didn't consider to post the whole code cause it's around 500 lines, including all constructors( manually implemented)
Topic archived. No new replies allowed.