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 will it be called char* ? and why, when I comment on a function with the char* parameter, will another function be called instead?

+4
source share
4 answers

This is because "ASDADS" converted to char * . Thus, the compiler generates code for the first function, which may correspond to the argument.

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

Take for example the following:

 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) , another function is called.

However, if you declare the constructor as explicit , you will receive an error message:

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

The type of the string literal (for example, "abc" ) is "array of const char". However, as a special rule, C ++ allows a standard conversion (deprecated!) To char * . Such a conversion is preferable to a custom conversion provided by the constructor string::string(const char *) . Thus, char* overloading wins while resolving overloading (zero user conversions for char* as opposed to a single user transform for string ).

(in fact, I cannot find a standard link for this, on the contrary, in C.1.1 it is explicitly stated that char * p = "abc"; is β€œinvalid in C ++.” Any additional input is evaluated. Editing: it looks like this change from C ++ 03 to C ++ 11, and in C ++ 11 it's really illegal.)

+3
source

When you have both functions, there are two alternatives to choose from, and (char *) is better for your "ASDADS" argument. If you remove the function (char *), then there is the only function that wants a string. Therefore, the compiler creates a string using a string constructor that accepts char *.

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

0
source

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

0
source

Source: https://habr.com/ru/post/1397274/


All Articles