user1381456
user1381456

Reputation: 27

concatenate char * to string

I have a function which is expecting a string, I was wanting to concatenate const char * to a string to be returned.

Here is example code to help illustrate this scenario:

void TMain::SomeMethod(std::vector<std::string>* p)
{
  p->push_back(TAnotherClass::Cchar1 + "/" + TAnotherClass::Cchar2);
}

and here is the other class these are from:

class TAnotherClass
{
 public:
   static const char * Cchar1;
   static const char * Cchar2;
};

const char * TAnotherClass::Cchar1 = "Home";
const char * TAnotherClass::Cchar2 = "user";

im getting the following error: invalid operands of types 'const char*' and 'const char*' to binary operator +

Why is this not valid? please help

Upvotes: 2

Views: 2615

Answers (2)

Edward Strange
Edward Strange

Reputation: 40859

Because you're trying to add two pointers. The + operator can't be overridden for char*.

You can do this:

p->push_back(std::string(TAnotherClass::Cchar1) + "/" + TAnotherClass::Cchar2);

Keep in mind the fact that std::string(...) as used above is a C-style cast using functional notation. It's equivalent, in this case, to static_cast<std::string>(...).

Whether you allow function style casts in your code is up to you. Some policies are against ALL C-style casts. In my previous workplace this particular use of them was allowed, but no other.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

char const* cannot be used with + operator, as the error says.

What you need to do is this:

p->push_back(std::string(TAnotherClass::Cchar1) + "/" + TAnotherClass::Cchar2);
          //^^^^^^^^^^^^ notice this

It creates a temporary object of type std::string, then you can use + with it. It concatenates the strings, creating temporaries all the way, and finally passes the final string to push_back.

Apart from that, as @Konrad noted in the comment, don’t pass a pointer into the method, use a reference instead, as:

void TMain::SomeMethod(std::vector<std::string> & p) //<-- note & 
{
  p.push_back(std::string(TAnotherClass::Cchar1)+"/"+TAnotherClass::Cchar2);
}

Upvotes: 6

Related Questions