我怎样才能声明一个常量数据成员但直到以后才初始化它?

Tay*_*ite 5 c++ initialization declaration

假设在我的 main 方法中,我声明了一个 const int 数组指针,指向在堆上创建的数组。然后我想在构造函数 TryInitialize() 中初始化它的值(使用内存地址),然后将它们打印出来。这不起作用,我想知道我做错了什么?谢谢!

#include "stdafx.h"
#include "part_one.h"
#include <string>
#include <iostream>

using namespace std;

string createTable(unsigned int* acc, double* bal, int n) {
    string s;
    char buf[50];

    for (int i = 0; i < n; i++) {
            sprintf_s(buf,"%7u\t%10.2f\n",acc[i], bal[i]);
            s += string(buf);
    }

    return s;
}



int _tmain(int argc, _TCHAR* argv[])
{

    const int *tempInt = new const int[4];
    TryInitialize(tempInt);
    std::cout << tempInt[1] << endl;

    system("pause");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我的构造函数的代码:

#include "part_one.h"


TryInitialize::TryInitialize(void) {

}

TryInitialize::TryInitialize(int constInt[]) {
    constInt[0] = 8;
    constInt[1] = 0;
    constInt[2] = 0;
    constInt[3] = 8;
}
Run Code Online (Sandbox Code Playgroud)

Csq*_*Csq 3

您不应该更改const值。

对于您想要完成的任务,我建议声明一个非常量指针和一个常量指针,并在初始化后将非常量指针分配给常量指针:

int _tmain(int argc, _TCHAR* argv[])
{
    const int *tempTempInt = new int[4];
    TryInitialize(tempInt);
    const int* const tempInt = tempTempInt;
    std::cout << tempInt[1] << endl; //this is now constant.

    system("pause");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

另请注意指针声明中 const 的位置:

const int* const tempInt = tempTempInt;
Run Code Online (Sandbox Code Playgroud)

在上面的声明中,第二个const意味着你不能改变指针;第一个const意味着您无法更改指向的值。