C++ 的 内联变量

等级 5499 次按键

从 C++17 起,inline static 成员可以直接在类内初始化,即使是 string 和 vector 这样的类型,也无需在 .cpp 文件中另行定义。printConfig() 输出它们,也可以通过 Config::version 直接访问。

C++ 代码

1class Config {
2public:
// inline static:在类内初始化,无需另行定义
3 inline static const string version = "1.0.0";
// 编译期已知的常量
4 inline static constexpr int maxConnections = 100;
// 对 vector 这样的类类型同样适用
5 inline static const vector<string> supportedFormats = {"json", "xml", "csv"};
6
// 静态函数:无需对象即可调用
7 static void printConfig() {
8 cout << "Version: " << version << endl;
9 cout << "Max connections: " << maxConnections << endl;
10 cout << "Formats: ";
// 输出每种格式并跟一个空格
11 for (const auto& fmt : supportedFormats) cout << fmt << " ";
12 cout << endl;
13 }
14};
15
// 输出版本、最大连接数和格式
16Config::printConfig();
// 通过类名访问:输出“Direct access: 1.0.0”
17cout << "Direct access: " << Config::version << endl;

运行结果

Version: 1.0.0
Max connections: 100
Formats: json xml csv 
Direct access: 1.0.0
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 27
  • "× 18
  • ;× 11
  • :× 10
  • (× 3
  • )× 3
  • {× 3
  • }× 3
  • =× 3
  • ,× 2

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习