gpt4 book ai didi

c++ - 尾随返回类型供引用

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:19 27 4
gpt4 key购买 nike

考虑以下代码。

#include <iostream>

class A {

public:
using T = float;
A(const T& x)
{
m_value = x;
}

T& value();

private:
T m_value;
};

// A::T& A::value()
// {
// return m_value;
// }

auto& A::value() -> T &
{
return m_value;
}

int main()
{
A a(10.0);
std::cout << a.value() << std::endl;

return 0;
}

当使用 C++11 编译时,出现以下错误。

error: ‘value’ function with trailing return type has ‘auto&’ as its type rather than plain ‘auto’
auto& A::value()->T &
^

等效代码(注释函数)工作正常。但我想使用尾随返回类型。

最佳答案

如果你想使用尾随返回类型,除了 auto 说明符之外,你不能在通常放置返回类型的地方使用任何其他内容:

auto  A::value()->T &
// ^ no '&' here
{
return m_value;
}

虽然您在 -> 之后指定的类型已经是一个引用,所以不用担心。

关于c++ - 尾随返回类型供引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47538783/

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