c++ - 以这种方式比较字符串是一种好风格吗?

标签 c++ comparison operator-overloading c-strings c++17

<分区>

我想在 .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它不将 classenum 作为其操作数,这意味着您无法更改它们与内置类型一起使用的行为。

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/

相关文章:

c++ - 用浮点任意精度 C++ 库改造现有代码,有成功的机会吗?

perl - 我如何比较 Perl 中的 md5 校验和?

c++ - 数组和比较的问题……在 if 的下面放什么来让僵尸在每一轮都向 sp 移动?

c++ - 不同类型的运算符

c++ - 在 C++ 中重载 [] 以返回左值

javascript - 有哪些工具可用于代码比较或并排比较?如何查找 Javascript 中的错误?

c++ - 检查整个数组是否为空

c++ - setter / getter 和分层数据结构

c++ - stringstream 和 double 的精度问题

c++ - 为什么我们在 C++ 中使用返回数据结构的函数?