在C++ Primer,第5版中阅读一个练习的答案,我找到了这段代码:
#ifndef CP5_ex7_04_h
#define CP5_ex7_04_h
#include <string>
class Person {
std::string name;
std::string address;
public:
auto get_name() const -> std::string const& { return name; }
auto get_addr() const -> std::string const& { return address; }
};
#endif
Run Code Online (Sandbox Code Playgroud)
是什么
const -> std::string const&
Run Code Online (Sandbox Code Playgroud)
这个意思是什么意思?
Bat*_*eba 21
auto get_name() const -> std::string const& { return name; }
是等效的尾随返回类型表示法
std::string const& get_name() const { return name; }
请注意,在使用一种语法声明函数并使用另一种语法定义函数的意义上,等价是精确的.
(这是C++标准的一部分,包括C++ 11).
该部分-> std::string const&
是尾随返回类型,是自C++ 11以来的新语法.
第一个const
说它是一个const
成员函数.可以在const
类型的对象上安全地调用它Person
.
第二部分只是告诉返回类型是什么 - std:string const&
.
当需要从模板参数推导出返回类型时,它很有用.对于已知的返回类型,它不比使用更有用:
std::string const& get_name() const { return name; }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1366 次 |
最近记录: |