overloading operator =

Trying to add functionality to string without changing string (or other class/type)
This works
1
2
3
4
5
6
string operator +(const string &str,const int i);
Usage:
string s = "123";
int    i = 345;

 string c=s+i;


Why not this
1
2
3
4
string operator =(string &str,const int i);
Usage:
string s;
s=123;

error: `std::string operator=(std::string&, int)' must be a nonstatic member function


It's telling you it must be a non-static member function. Either that or the string class has to tell it that it's its friend.

How about you make your own AdvString class that has these and then you just manipulate an internal std::string instead?
closed account (EzwRko23)
If you are doing this just for learning - ok, do it.
But in serious work, please don't invent yet another string class, or yet another implicit conversion from Foo to Baz just to save you typing... There are just too many of them.


[joke]
What is the one thing every programmer should do in his lifetime?
1. C++ programmer: create a string class
2. PHP programmer: create a CMS
3. Java programmer: create a web framework
4. Ruby programmer: write a blog post describing why RoR is the best framework
[/joke]
I would avoid overloading an operator for that. The intention just isn't clear enough. Account for associativity and then consider the result:

1
2
3
4
5
string a;
int b;

a + b // this expression should return a string, right?
b + a // what about this one? 

[joke]
What is the one thing every programmer should do in his lifetime?
1. C++ programmer: create a string class
2. PHP programmer: create a CMS
3. Java programmer: create a web framework
4. Ruby programmer: write a blog post describing why RoR is the best framework
[/joke]


5. Perl programmer: create the most perfect regular expression that can handle all possible combination and permutation
I was just doing for learning

I got the answer

+ is implemented as non-member function so we can overload without changing string implementation
http://www.cplusplus.com/reference/string/operator+/
string operator+ (const string& lhs, const string& rhs);

= as a member function
http://www.cplusplus.com/reference/string/string/operator=/
string& operator= ( const string& str );

One more question.
I like QString. - http://doc.qt.nokia.com/4.7/qstring.html
Is there a way to use it (alone) in my code ,without downloading/building the whole qt library.
A header file version?
Topic archived. No new replies allowed.