gpt4 book ai didi

c++ - != 运算符重载的参数问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:22:53 25 4
gpt4 key购买 nike

我正在尝试为 != 运算符定义一个重载。我的代码如下。 (更新:过时的代码。如果两个文章指针之一指向 NULL,此代码将崩溃。)

bool ArticleContainer::ArticleIterator::operator!=(const ArticleIterator& artit) {
if (this->article == NULL && artit.article == NULL)
return false;
else if (this->article->GetID() != artit.article->GetID())
return true;
else if (this->article->GetName() != artit.article->GetName())
return true;
else
return false;
}

当我在它的第一行代码上放置一个断点时,我在调试器中看到了这一点。

this - 0x22fedc

artit - Unable to create variable object

显然该函数无法访问 artit,因此它崩溃了。我做错了什么?

编辑:调用发生在这里。

for (ArticleContainer::ArticleIterator art = cont.Begin(); art != cont.End(); art++) {
cout << art << "\n";
}

基本上,我会遍历文章列表,直到遇到哨兵。

我刚刚在 for 循环之前测试了 cont.End():

const ArticleIterator& End() const { return *tail; }

尾部:

Name : tail
Details:0x571900

编辑:operator++代码如下:

void ArticleContainer::ArticleIterator::operator++(int i) {
this->article = this->next->article;
this->next = this->next->next;
}

最佳答案

我认为你的代码的意图是错误的,但从技术上讲你可以试试这个:

bool ArticleContainer::ArticleIterator::operator!=(const ArticleIterator& artit) {
if (article == NULL && artit.article == NULL)
return false;
if (article == NULL || artit.article == NULL)
return true;
if (article->GetID() != artit.article->GetID())
return true;
if (article->GetName() != artit.article->GetName())
return true;
return false;
}

但是,即使只考虑技术方面,我也宁愿用 operator== 来表达 operator!=

干杯,

关于c++ - != 运算符重载的参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4016620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com