【问题标题】:returning a pointer and changing what it points to返回一个指针并更改它指向的内容
【发布时间】:2018-02-02 11:32:21
【问题描述】:

我正在尝试返回一个指针并更改它所指向的内容,但我似乎无法让它工作。我是这样做的:

class someClass
{
    public:
        int *& foo();
    private:
        int * ptr = 5;
};

int *& someClass::foo()
{
    return ptr;
}
int main()
{
    int * ptrTwo = foo();
    ptrTwo = NULL;
    return 0;
}

我希望这会将 ptr 更改为 NULL。发生的事情是 ptr 不受影响,只有 ptrTwo 更改为 NULL。

【问题讨论】:

  • 什么是ptr,它在哪里声明或定义?说起来,className的定义在哪里?
  • 请显示minimal reproducible example。您实际上想要达到什么目的?
  • int x = 123; int& f() { return x; } /*...*/ int y = f(); y = 0;的情况一样,x不变。指针没有什么特别之处。
  • @Dante 不,你没有。
  • @Dante 您的问题中没有足够的信息,而且我不是唯一一个这么认为的人。您应该出示minimal reproducible example 并说明您期望发生的事情以及实际发生的事情。

标签: c++ pointers


【解决方案1】:

你可能想要这个:

#include <cstdio>

class className
{
public:
  int *ptr = (int*)1;
  int *& foo();
};

int *& className::foo()
{
  return ptr;
}

int main()
{
  className instance;

  int *& ptrTwo = instance.foo();
    // ^
    // |---- watch the &
    //
  printf("ptrTwo = %p\n", ptrTwo);

  ptrTwo = NUL     // this actually sets instance.ptr to NULL

  printf("instance.ptr = %p\n", (void*)instance.ptr);
}

顺便说一句,上面的代码是Minimal, Complete, and Verifiable example

输出将是这样的:

ptrTwo = 00000001
instance.ptr = 00000000

ptrTwo = 0x1
instance.ptr = (nil)

取决于您的平台。

Live demonstration

【讨论】:

    【解决方案2】:

    这里的问题是你正在返回一个对本地指针的引用。

    您应该将其更改为静态:

    static int ptr=&something;
    

    ...然后返回它。

    或者你应该返回一个全局声明指针的引用。

    【讨论】:

    • 感谢您对 StackOverflow 的首次贡献!请务必查看 Michael Walz 的答案。他提供了一个很好的例子,说明如何完整而清晰地回答一个问题。我们期待您未来的贡献。
    猜你喜欢
    • 2013-10-28
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多