简化复杂类型:类型别名如何提高代码可读性
C++11引入了using关键字来定义类型别名,比typedef更直观和灵活。
示例代码
#include <iostream>
#include <vector>
using IntVector = std::vector<int>; // 类型别名
int main() {
IntVector vec = {1, 2, 3};
for (auto val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
测试代码
#include <cassert>
void testTypeAlias() {
using IntPointer = int*;
int x = 10;
IntPointer p = &x;
assert(*p == 10);
}
int main() {
testTypeAlias();
std::cout << "All tests passed!" << std::endl;
return 0;
}