<分区>
我想在 .cpp
文件中使用它:
namespace
{
bool operator==(char const* const a, char const* const b) noexcept
{
return !::std::strcmp(a, b);
}
}
这种风格好吗?
编辑:
我认为完成同样事情的有品味的 c++1z 方法是使用新的 std::string_view
类进行比较。
<分区>
我想在 .cpp
文件中使用它:
namespace
{
bool operator==(char const* const a, char const* const b) noexcept
{
return !::std::strcmp(a, b);
}
}
这种风格好吗?
编辑:
我认为完成同样事情的有品味的 c++1z 方法是使用新的 std::string_view
类进行比较。
最佳答案
你不能overload operator它不将 class
或 enum
作为其操作数,这意味着您无法更改它们与内置类型一起使用的行为。
When an operator appears in an expression, and at least one of its operands has a class type or an enumeration type, then overload resolution is used to determine the user-defined function to be called among all the functions whose signatures match the following:
我建议您使用 std::string取而代之的是 char*
,它提供了 operator== .然后你就可以完全避免使用 std::strcmp()
和这种 c 风格的字符串函数。如果确实需要 c 风格的字符串,可以使用 std::basic_string::c_str()必要时将其转换回来。
关于c++ - 以这种方式比较字符串是一种好风格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766851/