c++ - 间接实例化一个指针

标签 c++

我有这样的东西:

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

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

我想从 b 实例化 a 所以 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);

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

最佳答案

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.

关于c++ - 间接实例化一个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12672559/

相关文章:

c++ - 符号 ":"在 C 和 C++ 中意味着什么?

c++ - 如何用支持 __LINE__ 和 __FILE__ 的内联函数替换我的 C++ 异常宏?

c++ - 解析 yyyy-MM-dd HH :mm:ss date time string?

c++ - 通过 BOOST_FOREACH 使我的 C++ 类可迭代

c++ - 给定基类方法的编译时覆盖

c++ - 是否可以使用自定义图形引擎渲染 Qt QWidgets 和 QML?

c++ - move 运算符=和复制运算符=之间的区别

c++ - VC2008 编译器错误打开 sbr 文件 (C2418 C1903 C2471)

c++ - 如何在不复制的情况下从 vector 中读取值?

c++ - Omnet中循环队列的初始化