为什么我不能添加指针 [英] Why can't I add pointers

查看:135
本文介绍了为什么我不能添加指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有非常类似的代码:

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

$ b $

推荐答案

为什么我在一个地方得到错误,

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,并转回指针。记住,这个解决方案需要非常关心指针算术,是你真正不应该做的事情。

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 ints, 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.

这篇关于为什么我不能添加指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆