如何声明一个常量数据成员,但直到以后才初始化它

How can I declare a constant data member but not initialize it until later?

本文关键字:初始化 常量 声明 何声明 一个 数据成员      更新时间:2023-10-16

假设在我的主方法中,我声明了一个 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,"%7ut%10.2fn",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;
}

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

#include "part_one.h"

TryInitialize::TryInitialize(void) {
}
TryInitialize::TryInitialize(int constInt[]) {
    constInt[0] = 8;
    constInt[1] = 0;
    constInt[2] = 0;
    constInt[3] = 8;
}

不应更改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;
}

还要注意在指针声明中放置 const 的位置:

const int* const tempInt = tempTempInt;

在上面的声明中,第二个const表示不能更改指针;第一个const表示不能更改指针值。

将指针声明为 const int*const修饰符表示您无法更改数组值。

要么删除const,要么为其创建一个初始值设定项方法,该方法可以分配数组并返回它(与构造函数不同)。

const int* init_my_array()
{
  int * ret = new int[4];
  ret [0] = 8;
  ret [1] = 0;
  ret [2] = 0;
  ret [3] = 8;
  return ret;
}
...
const int *tempInt = init_my_array();

你没有。为什么?因为如果它是 const,那么一旦对象被构造出来,它就不能被更改。注意:即使设置它,也会有效地从其未初始化的值更改其值,这违背了 const 的定义。