当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ enum of type char, ignored by the compiler or unexpected behaviour?

问题描述:

I did a little test with an enum, here is what I have:

enum anyoldname : char

{

aa = 'a', ab = 'b', ac = 'c', ad = 'd'

};

int main()

{

anyoldname i_have_an_enum_here = aa; // Would expect i_have_an_enum_here to be of type char?

std::cout << i_have_an_enum_here << std::endl;

return 0;

}

Output is: 98, unless I cast explicitly to char like so:

std::cout << (char)i_have_an_enum_here;

Or change anyoldname to char.

Why is the value 98 printed instead of b ?

By the way sizeof() returns 1, ie; 1 byte, a char.

网友答案:

Without the cast, the compiler first searches for an appropriate member function of std::ostream, and it finds one -- the one for an int. So it implicitly converts your 1-byte number of type anyoldname to an int and calls the member function.

Compiling your program with g++ 4.8.1, two definitions for ostream::operator<< are seen:

     U std::ostream::operator<<(std::ostream& (*)(std::ostream&))@@GLIBCXX_3.4
     U std::ostream::operator<<(int)@@GLIBCXX_3.4

The first one is for endl and the second one is for your enum.

With the explicit cast to char, the compiler is able to find a perfect match in the global std::operator<< function that takes an ostream and a char as an input. It then uses this function rather than doing an implicit cast (to an int again) in order to call an ostream member function.

The two symbols become:

     U std::ostream::operator<<(std::ostream& (*)(std::ostream&))@@GLIBCXX_3.4
     U std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char)

and your values are printed as characters rather than their decimal values.

网友答案:

If you are going to read The C++ Standard (I have only C++11 right now) section 7.2 paragraph 5:

Each enumeration defines a type that is different from all other types. Each enumeration also has an underlying type. The underlying type can be explicitly specified using enum-base; if not explicitly specified,...

Particularly this mean that your anyoldname actually a separate type which size the same as char (because its underlying type specified explicitly in a declaration). So, no reason to be implicitly convertible to char!

分享给朋友:
您可能感兴趣的文章:
随机阅读: