我正在学习 C++,我的目标是在控制台中漂亮地显示一个表格。我尝试使用
std::left
和 std::right
I/O 操纵器,但现在我查看我的代码,我无法弄清楚这些东西到底是什么以及它们采用什么样的机制。
到目前为止,每个函数调用都要求我至少在函数名称后面加上空括号
()
,这样就不会混淆什么是函数、什么不是函数。
cplusplus.com和cppreference.com让我了解到
left
和right
确实是函数,但是可以在不使用括号的情况下调用它们。
简而言之,为什么我可以将
left
放在任何不带括号的地方,但任何其他函数调用都需要我有括号 ()
?
另外,cplusplus.com上说
left
是一种叫做“操纵者”的东西,但我还是第一次听到这样的说法。我不知道“操纵者”一词的定义是什么,也不知道网站上的任何内容是否真正有意义。
std::left
和 std::right
I/O 操纵器1) 设置 I/O 流的字段对齐方式。要看到效果,还必须使用 std::setw
设置字段宽度 例如:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::left << '{' << std::setw(10) << "left" << "}\n"
<< std::right << '{' << std::setw(10) << "right" << '}';
}
输出:
{left }
{ right}
I/O 操纵器是函数,可以用
()
调用,但通常由 重载 <<
运算符 调用,该运算符将这些操纵器作为函数指针:
// func is a pointer to a function which accepts a reference
// to std.:ios_base, and returns a reference to std::ios_base
basic_ostream& operator<<(std::ios_base& (*func)(std::ios_base&)); // (18)
// I/O manipulators are functions:
// std::ios_base& left( std::ios_base& str );
std::cout << std::left
中实际发生的是:
std::cout.operator<<(&std::left);
<iomanip>
标头中的函数。