我正在尝试将类对象的内容写入文件。该对象有一个枚举类成员,我无法使用 ofstream 将其写入文件。
我收到以下错误。
error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘EnumClass_scope::EnumCass_name’)
任何线索都会有所帮助。
我正在尝试将类对象的内容写入文件。该对象有一个枚举类成员,我无法使用 ofstream 将其写入文件。
我收到以下错误。
error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘EnumClass_scope::EnumCass_name’)
任何线索都会有所帮助。
另一种选择是<<
为您的枚举手动重载运算符:
#include <iostream>
enum class ESomething
{
Nothing,
Something,
Everything,
};
std::ostream& operator<<(std::ostream& os, const ESomething& other)
{
switch (other)
{
case ESomething::Nothing:
os << "Nothing";
break;
case ESomething::Something:
os << "Something";
break;
case ESomething::Everything:
os << "Everything";
break;
default:
break;
}
return os;
// Alternatively: std::cout << std::underlying_type(other); return os;
}
int main()
{
ESomething hello = ESomething::Something;
std::cout << hello << '\n';
return 0;
}
您可以在哪里准确决定在每个单独的情况下输出什么,或者像其他答案提到的那样简单地将其转换为基础类型并输出。这是你的选择。
One way is to cast the enum type to the underlaying type. This can be done with already defined std::underlying_type_t
to get the internal representation of the enum.
template < typename T>
auto toUnderlayingType( T t )
{
return static_cast<std::underlying_type_t< T >>( t );
}
template < typename T, typename U = std::underlying_type_t< T > >
void readToEnum( U u , T& t )
{
t = static_cast< T >( u );
}
class Y
{
public:
enum class X
{
ONE,
TWO
} x;
Y(): x{X::ONE} { }
void Print()
{
std::cout << toUnderlayingType(x) << std::endl;
}
void Read()
{
std::underlying_type_t< X > tmp;
std::cin >> tmp;
readToEnum( x, tmp );
}
};
int main()
{
Y y;
y.Print();
}
But in the case of serialization it is even better to use a better representation of content and data. As reflection is still not part of c++ you have to convert the enum value to any useful output and back. Maybe you will write text like "ONE" instead of 0 to the file. But all this is to broad for this answer. There are a long list of serializer libraries like boost and cerial
And you have to check if the incoming value is a valid one. Having the example above and assign a numerical 3 to it, the enum value is invalid. That topic is already discussed here: What happens if you static_cast invalid value to enum class?
在写入之前将变量转换为整数。读取时使用整数临时变量。
std::fstream stream;
enum class Enum { ... };
Enum variable;
stream << static_cast<int>(variable);
int temporary;
stream >> temporary;
variable = static_cast<Enum>(temporary);
如果您使用其他类型定义 enum int
,请使用该类型。例如,使用enum class Enum : unsigned long long
,使用static_cast<unsigned long long>
。