c++ - 字符串问题

标签 c++ compare cstring

我正在使用一个 cstring 函数,该函数应该比较两个字符串 MyString 和 m2 的值。我有#include 所以它绝对不是那个。这些是我的错误。

(74) : error C2275: 'MyString' : illegal use of this type as an expression
(74) : error C2660: 'MyString::length' : function does not take 1 arguments
(76) : error C2275: 'MyString' : illegal use of this type as an expression

这是我从中获取它们的代码。

bool MyString::operator ==(const MyString &m2) const
{
    int temp = 0;

    if (length(MyString) = length(m2)) // 74
    {
        if (strcmp(MyString, m2))  // 76
        {
            temp = 1;
        }
        else
        {
            temp = 2;
        }
    }
    if(temp = 2)
    {
        return "true";
    }
    else
    {
        return "false";
    }
}

如有任何帮助,我们将不胜感激,谢谢。

最佳答案

问题:

  • 返回 true 或 false,而不是“true”或“false”
  • 您正在使用 = 而不是 == 进行比较(您在代码中两次使用 = 进行比较)
  • 要在 C++ 类中引用自己,您需要使用关键字 this 而不是类名。
  • 第 74 行应该是:

    if (length() == m2.length()) // 74
    
  • strcmp 采用 char* 而不是 MyString。
  • 第 76 行应该是:

    if (strcmp(this->c_str(), m2.c_str()))  // 76
    

在第 76 行中,假设类型 MyString 有一个函数 c_str(),它返回一个指向以零终止的 char[] 缓冲区的指针。


功能结构:

函数的结构真的很糟糕。考虑更像这样的事情:

bool MyString::operator ==(const MyString &m2) const
{
    if(this->length() != m2.length())
      return false;

    return !strcmp(this->c_str(), m2.c_str()));
}

注意:以上函数中this->可以省略。

关于c++ - 字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/624148/

相关文章:

ios - 将 CString 转换为 NSUTF16 编码的 NSString

c++ - vc6和vc7中的CString有什么区别?

尝试解析 CORBA 引用时出现 C++ 段错误

c++ - 无法关闭仅消息窗口 - C++

c++ - 函数中推导参数之前的默认模板参数?

c++ - 为什么我的 C++ 程序不计算 'e' 的更多位数?

Excel vba - 比较两个范围并找到不匹配项

c++ - 创建和比较两组卡片

python - 如何比较 pandas/python 中的两行重叠

c - 末尾带有垃圾字符的字符串数组