简体   繁体   中英

c++ function parameter char pointer and string

void callme(string a)
{
  cout<<"STRING CALLED"<<endl;
}

void callme(char * a)
{
  cout<<"char pointer called"<<endl;
}

int main()
{
   callme("ASDADS");
   return 0;
}

why is it that the char* will be called? and why when I comment out the function with the char* parameter, the other function will be called instead?

That's because "ASDADS" is convertible to char * . The compiler thus generates code for the first function it can match the argument to.

If you remove the prototype with char * , the compiler will look for functions that accept a parameter with an implicit cast from char * to the parameter type.

Take the following for example:

class A
{
public:
    A() {}
    A(int x) {}
};

//void foo(int x) {}
void foo(A x) {}

int main(int argc, char* argv[])
{
    int x = 3;
    foo(x);
}

if you comment out foo(int x) , the other function will be called.

However, if you declare the constructor as explicit , you'll get an error:

class A
{
public:
    A() {}
    explicit A(int x) {}
};

The type of a string literal (like "abc" ) is "array of const char". However, as a special rule, C++ allows a (deprecated!) standard conversion to char * . Such a conversion is preferred over the user-defined conversion furnished by the constructor string::string(const char *) . Thus the char* overload wins during overload resolution (zero user-defined conversions for char* as opposed to one user-defined conversion for string ).

(I can't actually find a standard reference for this; on the contrary, C.1.1 says explicitly that char * p = "abc"; is "invalid in C++". Any further input is appreciated. Edit: It seems like this is a change from C++03 to C++11, and in C++11 this is indeed flat-out illegal.)

When you have both functions there are two alternatives to pick from and (char *) fits better to your argument "ASDADS". If you remove the (char *) function then there is a single function that wants a string. So the compiler creates a string using a string constructor that takes a char *.

http://www.cplusplus.com/reference/string/string/string/

By default "ASDADS" is referenced by a char pointer. So 2nd version of callme() is used. If that is commented, compiler will try to match it with string and hence 1st version of callme() is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM