在尝试从c ++项目中删除警告时,我无法理解为什么第一个函数返回int会发出警告"警告:在函数返回类型上忽略类型限定符"但是返回std :: string的第二个函数不会发出此警告?
//first function
const int getX()
{
int x =9;
return x;
}
//second function
const std::string getTemp()
{
std::string test = "Test..";
return test;
}
Run Code Online (Sandbox Code Playgroud)
const 原始类型对返回值没有影响,因为您无法修改基本类型的右值.
getX() = 5; // error, even if getX() returns a non-const int.
Run Code Online (Sandbox Code Playgroud)
但是对于类类型,const可以有所不同:
std::string s = getTemp().append("extra");
// error if getTemp() returns a `const std::string`, but valid
// if getTemp() returns a non-const `std::string`.
Run Code Online (Sandbox Code Playgroud)