C++面向过程,char*,const char*,string类型参数与函数调用的关系

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*;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值