这个枚举的大小是多少,以字节为单位?C++
enum Cars { Toyota, Suzuki, Volkswa, Mitsubish, Alfarome, Holden, Bradleys };
Run Code Online (Sandbox Code Playgroud)
Sho*_*hoe 11
根据C++标准的§7.2/ 5,在您的情况下,基础类型不是固定的:
可以使用enum-base显式指定基础类型.对于作用域枚举类型,如果未明确指定,则基础类型为int.在这两种情况下,基础类型都被认为是固定的.[...]
这导致§7.2/ 7:
对于其基础类型未修复的枚举,基础类型是一个整数类型,可以表示枚举中定义的所有枚举器值.如果没有整数类型可以表示所有枚举器值,则枚举是不正确的.它是实现定义的,其中整数类型用作底层类型,除了底层类型不应大于int,除非枚举器的值不能适合int或unsigned int.如果枚举器列表为空,则基础类型就好像枚举具有值为0的单个枚举器一样.
总结一下,对于你的枚举,底层类型最多是一个int或者unsigned int.您可以通过sizeof以及类型来检查尺寸typeid.检查使用g ++验证结果的代码的示例(Visual C++不需要):
#include <iostream>
#include <typeinfo> // std::type_info
#include <type_traits> // std::underlying_type
using namespace std;
int const bits_per_byte = CHAR_BIT;
#ifdef __GNUC__
# include <cxxabi.h> // abi::*, free
# include <string> // std::string
auto display_name( type_info const& info )
-> string
{
int status;
char* demangled = abi::__cxa_demangle( info.name(), 0, 0, &status );
string result = demangled;
free( demangled );
return result;
}
#else
auto display_name( type_info const& info )
-> string
{ return info.name(); }
#endif // __GNUC__
enum Cars {
Toyota, Suzuki, Volkswa, Mitsubish, Alfarome, Holden, Bradleys
};
auto main() -> int
{
using Cars_type = typename underlying_type< Cars >::type;
type_info const& info = typeid( Cars_type );
cout << "This compiler is " << bits_per_byte*sizeof(void*) << "-bit.\n";
cout << "Underlying type is '" << display_name( info ) << "'.\n";
cout << "Size = " << sizeof( Cars ) << " bytes.\n";
}
Run Code Online (Sandbox Code Playgroud)
使用MinGW g ++(tdm64-1)5.1.0输出:
This compiler is 64-bit. Underlying type is 'unsigned int'. Size = 4 bytes.
大小取决于平台/实现。
在C ++ 11中,您可以指定基础类型(并因此指定大小)。在以下示例中,大小为1个字节:
#include <iostream>
#include <cstdint>
enum cars : std::uint8_t {
Toyota, Suzuki, Volkswa, Mitsubish, Alfarome, Holden, Bradleys
};
int main() {
cars my_car = cars::Toyota;
std::cout << sizeof(my_car) << std::endl;
};
Run Code Online (Sandbox Code Playgroud)
返回值:
1
Run Code Online (Sandbox Code Playgroud)
而
enum cars : std::uint32_t { ...
Run Code Online (Sandbox Code Playgroud)
返回值:
4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1659 次 |
| 最近记录: |