Odd behaviour of operator+()

J

Juha Nieminen

Consider this:

#include <iostream>
#include <string>

std::string operator+(const char* a, const std::string& b)
{
return std::string(a)+b;
}

int main()
{
std::string s = "abc" + "def";
std::cout << s << std::endl;
}

With gcc 3.3.5 it gives the rather strange error:

test.cc:11: error: invalid operands of types `const char[4]' and `const
char[4]
' to binary `operator+'

If I substitute the offending line with this:

std::string s = "abc" + std::string("def");

or even with this:

std::string s = operator+("abc", "def");

then it works just ok. However, as given above it doesn't. How come?
(References to the C++ standard preferred.)
 
T

Thorsten Kiefer

Hi,
there is no instance of operator+(const char *,const char *).
try this :

std::string operator+(const char* a, const char *b)
{
return std::string(a)+std::string(b);
}

I don't know why "std::string s = operator+("abc", "def");" works !?!


Regards
Thorsten
 
R

Roland Pibinger

Consider this:

#include <iostream>
#include <string>

std::string operator+(const char* a, const std::string& b)

BTW, this function is already implemented by std::(basic_)string.
 
A

Alf P. Steinbach

* Juha Nieminen:
Consider this:

#include <iostream>
#include <string>

std::string operator+(const char* a, const std::string& b)
{
return std::string(a)+b;
}

int main()
{
std::string s = "abc" + "def";
std::cout << s << std::endl;
}

You can overload an operator on class or enum type. You can not
overload the built-in operators. The usage

"abc" + "def"

invokes the built-in operator+, with invalid arguments.

Ignore the replies that indicate you can overload the built-in operator.

You can't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Crossword 2
operator<< and namespace?? 1
TF-IDF 1
Overloaded operator question 2
Crossword 14
Lexical Analysis on C++ 1
fixing absence of operator[] and at in list 3
How can I fix my pattern coding error in c++ 0

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top