0

For example, if you have an object of the std::string class, you can call the compare(string str) function as follows:

myString.compare(myOtherString);

How can I make my own function that I can call on a string in the same way? Example:

myString.contains(char[] chars);
Shadow
  • 3,926
  • 5
  • 20
  • 41

2 Answers2

1

You can't add member functions to existing classes in C++. Instead, write a non-member function

bool contains(std::string const & s1, std::string const & s2);

and call it as

contains(myString, myOtherString);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

You can't really do this in C++, and you shouldn't try. Sure, you could inherit from std::string and implement your methods, but then your methods will be unusable from regular strings. In C++ we do not try too hard to make everything a class method--free functions are functions too!

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    You could try, and end up with something like http://www.slideshare.net/phil_nash/c-extension-methods-18678294. But don't do this at home. – Mike Seymour Sep 09 '14 at 12:32