std::basic_string<CharT,Traits,Allocator>::front

< cpp‎ | string‎ | basic string
CharT& front();
(C++20 前)
constexpr CharT& front();
(C++20 起)
const CharT& front() const;
(C++20 前)
constexpr const CharT& front() const;
(C++20 起)

返回到字符串中首字符的引用。如果 empty() == true,那么行为未定义。

参数

(无)

返回值

到首字符的引用,等价于 operator[](0)

复杂度

常数。

注解

在 libstdc++ 中,front() 不能在 C++98 模式中使用。

示例

#include <iostream>
#include <string>
 
int main()
{
    std::string s("Exemplary");
    char& f1 = s.front();
    f1 = 'e';
    std::cout << s << '\n'; // "exemplary"
 
    std::string const c("Exemplary");
    char const& f2 = c.front();
    std::cout << &f2 << '\n'; // "Exemplary"
  }
}

输出:

exemplary
Exemplary

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 534 C++98 std::string 没有成员函数 front() 已添加

参阅

访问最后的字符
(公开成员函数)