Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add member functions in built-in classes in c++?

I want to add a new member function "charReplace" to the string class. The function will replace all the occurances of one character with another character. So I prepared a sample code.

#include <iostream>
#include <string>

std::string string::charReplace(char c1, char c2) { //error in this line
    while(this->find(c1) != std::string::npos) {
        int c1pos = this->find(c1); //find the position of c1
        this->replace(c1pos, 1, c2); //replace c1 with c2
    }
    return *this;
}

int main() {
    std::string s = "sample string";

    s.charReplace('s', 'm') /* replace all s with m */

    std::cout << s << std::endl;
}

But it is not working. I am getting the following error in line 4 while compiling.

error: 'string' does not name a type

I know that it is quite easy to get the same result by creating a non-member function. But I want to do it using a member function. So, is there a way to do this in c++?

P.S. I am still new with c++. I have been using it for a few months only. So, please try to make your answer easy to understand.

like image 442
Tanmoy Krishna Das Avatar asked Aug 06 '15 08:08

Tanmoy Krishna Das


1 Answers

you can't. this is C++, not JavaScript (where you can prototype any classes).

your options are:

  1. inheritance
  2. composition
  3. free standing functions
like image 168
David Haim Avatar answered Sep 27 '22 23:09

David Haim