间接实例化指针

时间:2012-10-01 11:39:50

标签: c++

我有这样的事情:

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

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

我想从a实例化b,因此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);

我想尽可能以这种方式实例化全局变量。

2 个答案:

答案 0 :(得分:3)

您需要参考:

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

ab的任何更改都会影响另一个。

答案 1 :(得分: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

Please consult a good C++ book for details.