自动类型推导(auto type deduction)
auto
“自动类型推导” 实际上与 “attribute” 一样,是编译阶段的特殊指令,指示编译器去计算类型。
类型别名(type alias):
using uint_t = unsigned int // 别名在左边,原名在右边
typedef unsigned int uint_t // 原名在左边,别名在右边
属性(attribute):
[[noreturn]] // 属性标签
// 函数不会返回任何值
int func(bool flag) {
throw std::runtime_error("...");
}
在 C++ 11,你可以在类声明变量的同时给它赋值,实现初始化。
class DemoInit final {
private:
int a = 42;
string s = "Hello World!";
vector<int> v{1, 2, 3};
public:
DemoInit(int x) : a(x) {}
在类成员变量初始化的时候,目前的 C++ 标准不允许使用 auto
推导类型。
class A final {
auto a = 10; // 错误,类里不能使用 auto 类型推导
}
规则:
auto
总是推导出 ”值类型“,绝不是 ”引用“;auto
可以附加上 const
、volatile
、&
这样的类型修饰符,得到新的类型。auto x = 10L // auto 推导为 long, x 是 long
auto& x1 = x // auto 推导为 long, x1 是 long&
auto* x2 = &x // auto 推导为 long, x2 是 long*
const auto& x3 = x // auto 推导为 long, x3 是 const long&
auto x4 = &x3 // auto 推导为 const long*, x4 是 const long*