解释C ++指针初始化

时间:2015-07-08 13:29:28

标签: c++

int value = 3;
int *pValue1 = &value;
int *pValue2(pValue1);
cout << (*pValue1) << " " << (*pValue2);

在上面的代码中,如果你注意到我写了

int *pValue2(pValue1); 

而不是

int *pValue2 = new int;
pValue2 = pValue1;

仍在努力并给出正确的结果。 任何人都可以向我解释在这种情况下调用哪个默认函数或构造函数?

2 个答案:

答案 0 :(得分:2)

int *pValue2(pValue1);

相当于

int* pValue2 = pValue1;

只需分配到pValue2 pValue1(分配给变量pValue2的{​​{1}}地址。)

答案 1 :(得分:1)

如果除了引用的值之外还打印指针本身(地址),差异应该是显而易见的:

#include <iostream>
using namespace std;

int main() {
    int value = 3;
    int *pValue1 = &value;
    int *pValue2(pValue1);
    int *pValue3 = new int;
    cout << pValue1 << " " << pValue2 << " " << pValue3 << endl;
    cout << *pValue1 << " " << *pValue2 << " " << *pValue3 << endl;

    pValue3 = pValue1;
    cout << pValue1 << " " << pValue2 << " " << pValue3 << endl;
    cout << *pValue1 << " " << *pValue2 << " " << *pValue3 << endl;

    return 0;
}

您还会看到在new int之后,指针指向的内存包含未初始化的数据。