char*,const char*,string类型参数与函数调用的关系
#include<iostream>
#include<string>
using namespace std;
void func(string& s) {
cout << "1" << endl;
}
void func(char* s) {
cout << "2" << endl;
}
void func(const char* s) {
cout << "3" << endl;
}
int main()
{
char s1[] = "hello";
string s2 = "hello";
func("hello"); //3
func(s1); //2
func(s2); //1
}
一、为什么
"hello"调用传入的是const char类型;
s1调用传入的是char类型;
s2调用传入的是string类型;
二、还有呢
把const char注释掉,则"hello"无法被调用,可以调用const string类型;
把char注释掉,s1会返回3;
把string注释掉,则s2无法被调用;
三、是这样
const char只能调用带const的,优先char;
string只能调用带string的,例如:string,string&,const string;
char可以调用string,反过来string不能调用char*;