Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Custom Functions for Strings in C++

I have only been using c++ for about a month now and I was wondering if it were possible to create your own custom functions for something like a string. For example to find the size of a string you do stringname.size() But what if I wanted to make a function like stringname.customfunction() were I get to decide what customfunction() does. I want to do this so I can create a .toLower() function that converts a whole string to lower. I'm sorry if this is a wierd question but any help would be greatly appreciated.

like image 792
Nicholas Ramsay Avatar asked Nov 13 '15 08:11

Nicholas Ramsay


2 Answers

Yes you can create custom functions, but not directly as member functions of an existing class.

The simplest and therefore best approach is to just create freestanding functions.

That means that you'll call it like customfunction( s ).

like image 192
Cheers and hth. - Alf Avatar answered Oct 09 '22 08:10

Cheers and hth. - Alf


You can achieve this by creating you own string class, but as I've undertood you mean calling something like "THE String".toLower() as in python for example. This is actually imposible in c++ as far as I know.

Once again your best chance is do your own class so you can call someting like MyString("THE String").toLower(). Or just create a function toLower that takes an string and return an string toLower("THE String")

like image 43
Netwave Avatar answered Oct 09 '22 10:10

Netwave