逻辑比较 == 运算符重载
Logical Comparison == operator overload
我需要做一些逻辑比较并返回一个布尔答案。
以下是.cpp文件中的代码:
bool MyString::operator==(const MyString& other)const
{
if(other.Size == this.Size)
{
for(int i = 0; i < this.Size+1; i++)
{
if(this[i] == other[i])
return true;
}
}
else
return false;
}
这是从主文件调用的内容.cpp:
if (String1 == String4)
{
String3.Print ();
}
else
{
String4.Print ();
}
以下是我得到的编译错误:
error: request for member `Size` in `this`, which is of non-class type `const MyString* const`
error: no match for `operator[]` in `other[i]`
this
是一个指针,因此你必须取消引用它:
this->Size;
我也认为你的operator==
逻辑是有缺陷的 - 在这里,它返回true
如果任何字符等于第二个字符串中相同位置的字符。将循环更改为
for(int i = 0; i < this->Size+1; i++)
{
if(this[i] != other[i])
return false;
}
并放置return true;
而不是代码的最后一部分(else
子句)来比较整个字符串。
正如 Seth 所提到的,您不能像上面一样在this
上使用 operator[]
- 这样它被视为数组(即 this[i]
真的很*(this + i)
- 所以不是你想的那样)。请改为访问您的内部存储成员。
代码问题:
-
this[i]
:您显然想在此处访问字符串的第 i 个字符。这不是这样做的。假设你的类重载operator[]
,你需要(*this)[i]
。或者,您可以直接访问字符串的内部表示形式。 -
if(this[i] == other[i]) return true;
: 想想这对比较字符串"A1"和"AB"意味着什么。 -
for () {...}
: 退出循环时会发生什么?如果比较设法通过循环而不返回,则需要返回一些内容。
您尚未指定是否可以使用C++标准算法。在这里,您已经说明了使用手写循环和std::equal
算法的两个版本:
//#define USE_STD_ALGORITHM 1 // uncomment to enable std::equal version
#include <cassert>
#include <algorithm>
#include <stdexcept>
// NOTE: partial simplest definition for the test and presentation purposes only.
struct MyString
{
MyString(char const* s, std::size_t size) : data(s), Size(size) {}
char const& operator[](std::size_t index) const;
bool operator==(const MyString& other) const;
private:
char const* data;
std::size_t Size;
};
char const& MyString::operator[](std::size_t index) const
{
if (index < Size)
return data[index];
throw std::out_of_range("index invalid");
}
bool MyString::operator==(const MyString& other) const
{
if (this->Size == other.Size)
{
#ifdef USE_STD_ALGORITHM
return std::equal(data, data+Size, other.data);
#else
bool equal = true;
for(std::size_t i = 0; i < this->Size; ++i)
{
if((*this)[i] != other[i])
{
equal = false;
break;
}
}
return equal;
#endif
}
return false;
}
int main()
{
char const* a = "abc";
char const* b = "abc";
MyString sa(a, 3);
MyString sb(b, 3);
assert(sa == sb);
char const* c = "adc";
MyString sc(c, 3);
assert(!(sa == sc));
char const* d = "ab";
MyString sd(d, 2);
assert(!(sa == sd));
}
祝你好运!
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板