Replicating Python functions in C++ -
this question has answer here:
i've switched c
oop languages - c++
, python 3.4
i noticed there quite-a-lot things python
c++
can't beat 1 of them being ease of calling functions.
so i've decided somehow implement python-way of making function calls in c++, using stl.
i started off 'string' class.
in python, can this:
str="hello world " str.strip().split()
and first, strip-off trailing whitespaces @ end of string , split string in 2 halves @ at whitespace
now that's neat , i'd love able call functions way, ie, object.func1().func2().func3()
, on
as have absolutely no idea stl class 'string', started off own made class 'mystring'
class mystring { string str; public: //constructor mystring(string str) { setter(str); } //setter function mystring& setter( string str ) { this->str=str; return *this; } //getter_str function string getter_str() { return str; } unsigned int getter_size() { return str.size(); } //modifier function(s) mystring& split(char x='\0') { string temp=""; for(int i=0; i<str.size(); i++) { if(this->str[i-1] == x) break; temp += str[i]; } this->str=temp; return *this; } mystring& strip() { for(int i=this->str.size() - 1; i>=0; i--) { if(this->str[i] == ' ') this->str.erase(i); else if(isalnum(this->str[i])) break; } return *this; } };
to test class , member functions, used following main()
int main() { //take user-defined string-type input string input; cout<<"enter string: "; getline(cin,input); // create object of class 'mystring' // , initialise input given user mystring obj(input); //take character @ string must split cout<<"\nenter character split string at: "; char x; cin>>x; //display original input cout<<"\n\nthe user entered: "<<obj.getter_str(); cout<<"\nsize = "<<obj.getter_size(); obj.strip().split(x);// <--- python style function call cout<<"\n\nafter strip , split: "<<obj.getter_str(); cout<<"\nsize = "<<obj.getter_size(); return 0; }
and works
so, here's question:
how can create , use same split
, strip
functions c++ stl string class
? possible use our own created methods stl?
every suggestion welcome.
you can extend class std::string , use extended class. class have functionality of stl string plus additional methods.
class mystring: public std::string { ... };
Comments
Post a Comment