不能将类型为‘std::string&’的非 const 引用初始化为类型为‘const char*’的临时变量

#include 
#include 
#include 
#include 
using namespace std;
void bar(string &s){
    std::cout<< s<< std::endl;
}
int main(){
  bar("hello");
}

报错原因:

hello作为临时对像是const类型,而bar这个函数的参数是非const类型,所以报错

正确写法:

#include 
#include 
#include 
#include 
using namespace std;
void bar(const string &s){
    std::cout<< s<< std::endl;
}
int main(){
  bar("hello");
}


你可能感兴趣的:(c++)