Sep 29, 2014 at 3:46pm UTC
i'm trying overloading the assigment operator without sucess :(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
class String
{
private :
string b="" ;
public :
String(string s="" )
{
b=s;
}
String& operator =(const string &s)
{
b=s;
return *this ;
}
String& operator =(const String &s)
{
b=s.b;
return *this ;
}
operator string()
{
return b;
}
};
String test="hi" ;
so what i did wrong with my class?
error message: "conversion from 'const char [3]' to non-scalar type 'String' requested"
Last edited on Sep 29, 2014 at 3:47pm UTC
Sep 29, 2014 at 3:52pm UTC
"hi" gives you a const char* so you can make it work by adding a String constructor that takes a const char* as argument.
Sep 29, 2014 at 4:14pm UTC
I thought MiiNiPaa already explained that you can't do that.
Sep 29, 2014 at 4:16pm UTC
yes.. but i'm doing in a diferent way.. like you see with a new class
Sep 29, 2014 at 4:16pm UTC
It doesn't matter. The operands are still not of class type.
Last edited on Sep 29, 2014 at 4:18pm UTC
Sep 29, 2014 at 4:20pm UTC
thanks for correct me.
but tell me 1 thing(but forget the string)... the operator addition is correct?
Sep 29, 2014 at 4:23pm UTC
Yeah, but the explicit cast is not needed because the result is already of that type.
May I ask where you are going with this class? Will it have some extra functionality that a std::string doesn't have? Otherwise I don't see the point.
Sep 29, 2014 at 4:25pm UTC
yes.. is for extra functionality... but i wanted the operator addition too
Sep 29, 2014 at 5:38pm UTC
The problem here is that "hi" + "hello"
would call
const char * operator +(const char *, const char *);
Unfortunately, you can't overload operators for primitive types only.
You'd need to do this:
String test = String("hi" ) + "hello"
Then you'd create the first String, and then be calling:
String& String::operator +(const char * s2);
Sep 29, 2014 at 5:56pm UTC
but in some cases , we can use with 2 parameters(have seen samples).. so what isn't right?
Sep 29, 2014 at 9:02pm UTC
You can use 2 parameters. As long as at least one of them is not primitive type : not pointer, not integral value, not floating point value, not boolean.
What can you do: use C++11 feature and create a user defined string literal suffix, like _s and make it convert string literal to std::string. You will have to write something like "Hello" _s
Sep 30, 2014 at 11:54am UTC
"use C++11 feature and create a user defined string literal suffix"
how i can do it?