间接实例化指针
Instantiate a pointer indirectly
我有这样的东西:
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
详情请查阅一本好C++书。
你需要一个参考:
int* b = NULL;
int*& a = b;
对a
或b
的任何更改都将影响另一个。
相关文章:
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 为什么我不能引用指向实例化对象的函数的指针?
- 是否可以将指向未实例化的对象的指针用作C++中的变量?
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- 为共享指针C++单独实例化对象
- 为什么不能在实例化对基类的引用的同时实例化指向派生类的指针?
- 模板类实例化中的指针转换无效
- 实例化一个模板类,该类采用具有不同函数签名的构造函数中的函数指针
- 为什么当我在构造函数中创建线程时,实例化对象和对象的指针的行为不同
- make_pair并push_back基指针,并实例化基指针的向量
- 声明基类类型的指针,但随后通过指向子类来实例化它.这是良好的编程实践吗?
- 使用派生类实例化基类,而不在对象定义中使用指针
- (C++)用于实例化新对象并将其分配给指向相同对象类型的指针的 2D 向量的语法
- C 实例化对象,在没有指针的情况下,其他类构造函数中没有默认构造函数
- 用push_back()实例化对象时,如何将指针传递给对象的构造函数
- 如何在 C++ 中的构造函数中正确实例化指针数组
- 使用指针实例化模板类
- 为什么可以从实例化基类对象的投射指针调用非静态派生类方法
- 当我创建一个int指针并实例化一个数组时,数组在内存中发生了什么
- 如何使用智能指针实例化对象