问题描述
我的代码与此非常相似:
I have code very similiar to this:
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const
{
return (this + &right);//IN THIS PLACE I'M GETTING AN ERROR
}
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator-(const Iterator& right)const
{//substracts one iterator from another
return (this - &right);//HERE EVERYTHING IS FINE
}
err msg: Error 1 error C2110: '+' : cannot add two pointers
为什么我只在一个地方而不是两个地方都出现错误?
Why I'm getting an error only in one place and not in both?
推荐答案
C ++中禁止添加指针,只能减去两个指针.
Pointer addition is forbidden in C++, you can only subtract two pointers.
这样做的原因是两个指针相减得到一个逻辑上可以解释的结果-两个指针之间的内存偏移量.同样,您可以向指针减去或增加一个整数,这意味着向上或向下移动指针".向指针添加指针很难解释.生成的指针将代表什么?
The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent?
如果碰巧您明确需要一个指向内存中某个地址的指针,该地址的地址是另两个地址的总和,则可以将这两个指针转换为int
,添加int
s,然后转换回a指针.不过请记住,该解决方案需要非常注意指针算法,这是您真正不应该做的事情.
If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int
, add int
s, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.
这篇关于为什么我不能添加指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!