我正在使用一个 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/