gpt4 book ai didi

c++ - 为什么仅在基元的情况下才忽略函数返回类型的类型限定符?

转载 作者:太空狗 更新时间:2023-10-29 20:02:27 25 4
gpt4 key购买 nike

在尝试从 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;
}

最佳答案

原始类型的

const 对返回值没有影响,因为您不能修改原始类型的右值。

getX() = 5; // error, even if getX() returns a non-const int.

然而,对于类类型,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`.

关于c++ - 为什么仅在基元的情况下才忽略函数返回类型的类型限定符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com