1

我有这样的事情:

int* a = NULL;
int* b = *a;

b = new int(5);
std::cout << *a;
std::cout << *b;

我想实例化ab所以a值为 5。这可能吗?

编辑:

实际代码是这样的 -

int* a = null; //Global variable
int* b = null; //Global variable

int* returnInt(int position)
{
    switch(position)
    {
      case 0:
         return a;
      case 1:
         return b;
     }
}

some other function -

int* c = returnInt(0); // Get Global a

if (c == null)
    c = new int(5);

如果可能的话,我想以这种方式实例化全局变量。

4

2 回答 2

3

你需要一个参考:

int* b = NULL;
int*& a = b;

a对其中一个或b将影响另一个的任何更改。

于 2012-10-01T11:41:40.533 回答
3
int* a = NULL;
int* b = *a; //here you dereference a NULL pointer, undefined behavior.

你需要

int* b = new int(5);
int*& a = b; //a is a reference to pointer to int, it is a synonym of b
std::cout << *a;
std::cout << *b;

或者,a可以是对的参考int和同义词*b

int* b = new int(5);
int& a = *b; //a is a reference to int, it is a synonym of `*b`
std::cout << a;  //prints 5
std::cout << *b; //prints 5
a = 4;
std::cout << a;  //prints 4
std::cout << *b; //prints 4

有关详细信息,请参阅一本好的 C++ 书籍。

于 2012-10-01T11:42:22.977 回答