!= 运算符重载的参数问题
我正在尝试为 != 运算符定义重载。我的代码如下。 (更新:过时的代码。如果两个文章指针中的一个指向 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;
}
当我在其第一行代码上放置断点时,我在调试器中看到了这一点。
这个 - 0x22fedc
artit - 无法创建变量对象
显然该函数无法访问artit
,因此它崩溃了。我做错了什么?
编辑:调用发生在此处。
for (ArticleContainer::ArticleIterator art = cont.Begin(); art != cont.End(); art++) {
cout << art << "\n";
}
基本上,我会浏览一系列文章,直到遇到哨兵。
我刚刚在 for 循环之前测试了 cont.End()
:
const ArticleIterator& End() const { return *tail; }
With tail:
Name : tail
Details:0x571900
Edit:operator++ 代码如下:
void ArticleContainer::ArticleIterator::operator++(int i) {
this->article = this->next->article;
this->next = this->next->next;
}
I'm trying to define an overload for the != operator. My code is as follows. (Update: outdated code. If one of two article pointers points to NULL, this code will crash.)
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;
}
When I put a breakpoint on its first line of code, I saw this in the debugger.
this - 0x22fedc
artit - Unable to create variable object
Apparently the function can't access artit
, so it crashes. What am I doing wrong?
Edit: the call happens here.
for (ArticleContainer::ArticleIterator art = cont.Begin(); art != cont.End(); art++) {
cout << art << "\n";
}
Basically, I walk through a list of articles until I encounter the sentinel.
I just tested cont.End()
right before the for loop:
const ArticleIterator& End() const { return *tail; }
With tail:
Name : tail
Details:0x571900
Edit: operator++ code is as follows:
void ArticleContainer::ArticleIterator::operator++(int i) {
this->article = this->next->article;
this->next = this->next->next;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您的代码的意图是错误的,但从技术上讲,您可以尝试这样做:
但是,即使只考虑技术,我也宁愿用
operator!=
来表达operator!=
运算符==
。干杯&呵呵,,
I think the intent of your code is wrong, but technically you can try this:
However, even considering only the technical, I'd rather express
operator!=
in terms ofoperator==
.Cheers & hth.,
bool ArticleContainer::ArticleIterator::operator!=(const ArticleContainer::ArticleIterator& artit);
bool ArticleContainer::ArticleIterator::operator!=(const ArticleContainer::ArticleIterator& artit);