如何声明一个常量数据成员,但直到以后才初始化它
How can I declare a constant data member but not initialize it until later?
假设在我的主方法中,我声明了一个 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 的定义。
相关文章:
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 初始化常量字符* 数组
- 为什么MSVC14允许声明指向动态未初始化常量对象的指针
- C++初始化常量
- 在可变参数构造函数中初始化常量数组
- 使用数字初始化常量引用
- 如何在不初始化常量的情况下声明数组?
- 初始化常量静态 std::map unique_ptr作为值
- 为什么您可以初始化常量引用,但不能初始化来自右值的非常量引用
- 类中的初始化常量
- 如何初始化常量 CLSID
- 在类中初始化常量数组
- 在声明C++之后初始化常量变量
- C++初始化:常量全局与静态类成员的顺序
- 在头文件中声明并初始化常量
- 恒常性添加无效?错误:无法使用字符**初始化常量字符**
- 为什么我能够在构造函数中初始化常量
- 通过指针初始化常量矩阵<双精度,0,80>(来自 Dlib)
- C++构造函数:初始化常量引用时出现垃圾
- 用自身初始化C++常量变量