面试题答案
一键面试1. C++字符常量和字符串常量的底层存储及sizeof操作
字符常量
- 布局结构:在C++中,字符常量通常是一个单字符,占用一个字节的存储空间。例如,
'a'
在内存中以其对应的ASCII码值(97)存储,其类型为char
。 - sizeof操作:使用
sizeof
对字符常量进行操作,结果为1。例如,sizeof('a')
的结果是1,因为字符常量只占用一个字节。
字符串常量
- 布局结构:字符串常量是由零个或多个字符组成的序列,以空字符
'\0'
结尾。例如,字符串常量"hello"
在内存中实际存储为'h', 'e', 'l', 'l', 'o', '\0'
,占用6个字节。 - sizeof操作:
sizeof
对字符串常量操作时,返回的是包含结尾空字符在内的字节数。例如,sizeof("hello")
的结果是6,因为它包含了5个字符和1个结尾的空字符'\0'
。
2. C++模板元编程代码
#include <iostream>
// 模板特化基础情况
template<char... chars>
struct StringLength;
template<>
struct StringLength<> {
static constexpr std::size_t value = 0;
};
// 递归模板特化
template<char head, char... tail>
struct StringLength<head, tail...> {
static constexpr std::size_t value = 1 + StringLength<tail...>::value;
};
// 连接两个字符常量并获取长度
template<char c1, char c2>
struct ConcatAndLength {
static constexpr char result[] = {c1, c2, '\0'};
static constexpr std::size_t length = StringLength<c1, c2, '\0'>::value;
};
int main() {
// 示例使用
std::cout << "Length of \"ab\" is: " << ConcatAndLength<'a', 'b'>::length << std::endl;
return 0;
}
在上述代码中:
StringLength
模板类用于计算字符序列的长度。ConcatAndLength
模板类将两个字符常量连接成一个字符串常量,并使用StringLength
获取其长度。- 在
main
函数中,展示了如何使用ConcatAndLength
来获取连接后的字符串常量的长度并输出。