string + int!~

#include
#include
#include
using namespace std;

string operator+(const string& s, int i) {
stringstream result;
result << s << i;
return result.str();
}

int main()
{
string str = "CD" + 13342;
cout << str << endl;

system("PAUSE");
return 0;
}

Comments

  • [code]
    #include
    #include
    #include

    std::string operator+(
    std::string const &s,
    int const &i
    )
    {
    stringstream result;
    result << s << i;
    return result.str();
    }

    int main(
    void
    )
    {
    std::string str = "CD" + 13342;
    std::cout << str << std::endl;

    system("PAUSE");
    return 0;
    }
    [/code]

    Alright a few things first off to point out.

    The operator overload should take a constant int as well since that integer is not expected to change in the function.

    As for why:
    [code]
    ...
    std::string str = "CD" + 13342;
    ...
    [/code]
    does not invoke the overloaded operator is simple. "CD" is not a std::string. It is considered a [b]char const *[/b]. If you want to invoke the overload then you need to do the addition on a std::string object.

    Either of the following will work:
    [code]
    std::string str = std::string( "CD" ) + 13342;
    [/code]
    or
    [code]
    std::string str( "CD" );
    str = str + 13342;
    [/code]

    Regards.
    Neb

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion