-1

When I try to connect string objects with other strings i'll get a "basic_string" which is not accepted by my method.

I got the following error:

error: no matching function for call to ‘Class1::doSomething(std::__cxx11::basic_string)’

My main class:

using namespace std;
int main() {
    string s = "test";
    Class1* class1 = new Class1();
    class1->doSomething("some text " + s + " too");
}

My "class1":

using namespace std;
class Class1 {
     public:
         void doSomething(const char* sql) { 
              mysqli_query(connection, sql);
         }
}

Why I can't just "+" the strings together?

mkkagain
  • 45
  • 1
  • 9

1 Answers1

3

You can.

The error is not related to the +.

The error is because you are passing a std::string to a function that wants a const char*, and the two things are not the same.

Fixable, though, because std::string has a member function c_str() that gives you a C-style string out of its contents, precisely for this kind of occasion:

class1->doSomething(("some text " + s + " too").c_str());

As an aside, a minimal example would have been:

std::string str = "hi";
Class1 class1;
class1.doSomething(str);

Then you would have known already that the + were unrelated.

If Class1 is yours, you may find it more idiomatic to allow your class to accept a C++ string, only "converting" for the MySQL API when necessary:

void doSomething(const std::string& sql) {
    doSomething(sql.c_str());
}

void doSomething(const char* sql) { 
    mysqli_query(connection, sql);
}

(I've kept the original overload because if you originally had a C-string, constructing a std::string just for this function call would be wasteful.)

Now your original usage is fine.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055