简体   繁体   English

用++和 - 运算符在C ++中更改结构的地址

[英]Changing address of a struct in C++ by ++ and — operator

Is it possible to change the address of my current struct using the -- or ++ operator, ie: 是否可以使用 - 或++运算符更改当前结构的地址,即:

mystruct* test = existing_mystruct;
test++ // instead of using: test = test->next_p;

I was trying to use this, but it seems to be const and gives me an Error: assignment to this (anachronism): 我试图使用它,但它似乎是常量并给我一个错误:赋予这个(不合时宜):

struct mystruct {
    mystruct* next_p;
    mystruct* prev_p;

    void operatorplusplus  () { this = next_p; }
    void operatorminusminus() { this = prev_p; }
};

Objects have a constant address in memory while they exist. 对象在存在时在内存中具有恒定地址。 You may copy them to a new address, however. 但是,您可以将它们复制到新地址。

What you try to do is advance in a linked list. 您尝试做的是在链表中前进。 And it may be done with those operators if you overload them. 如果你重载它们,它可以用那些运算符完成。 But you will need to define that in a special handle class to wrap over the list nodes. 但是您需要在特殊的句柄类中定义它以包裹列表节点。

EDIT 编辑

The code for what I describe will look somewhat like this: 我描述的代码看起来有点像这样:

class mylist
{
  struct mynode
  {
    //data
    mynode* next;
    mynode* prev;
  } *curr;

public:
 mylist& operator++() {curr = curr->next; return *this;}
};

Naturally you'd wanna do boundry checks and such, but that's the general idea. 当然,你想做边界检查等等,但这是一般的想法。

不, this指针的类型是mystruct * const ,这意味着它的地址是mystruct * const更改的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM