是否可以强制编译器在我的类中传播常量限定符,以便为构造函数提供常量指针?考虑以下代码:
struct T
{
T(int * a, int * b):
a(a), b(b) {}
int * a;
int * b;
};
int a = 1, b = 2;
const int * aRef = &a;
const int * bRef = &b;
const T obj(aRef, bRef); // error
这显然是不允许的,因为构造函数接受 int *
,而不是 const int *
。有什么方法可以达到同样的效果,如果不打算修改 const
对象中的 a
和 b
处的数据类 T
?
编辑 下面是一个更接近实际问题的稍微复杂的例子。想象一下,我按顺序传递了一些大型 int[]
数组(例如,连续 1000 个整数),我想评估 k
中元素的运行最大值-th 位置(即运行最大值也是 1000-int vector )。当我将 const int *
传递到传入数组的开头时,我设计了一个结构
struct ArrayWithMax
{
public:
ArrayWithMax(int * array) : array(array) {}
void Max(const ArrayWithMax& rhs);
private:
int * array;
}
ArrayWithMax::Max
显然会循环遍历两个数组,并分配最大值 (max(this->array[k], rhs.array[k]
) 到对象的 array
。为简洁起见,我将跳过代码。
现在,我将存储结果的变量必须是非常量(因为最大数组的元素会改变)。然而,我收到的更新是 const int *
。对我来说,最简单的方法是从 const int *
初始化 const ArrayWithMax
,这正是问题试图实现的目标。
最佳答案
看起来你想要的是:
const T obj(aRef, bRef);
导致无法修改指针指向的整数的对象。这意味着成员指针可以是 int const* const
或 int const*
。
实际情况是,const
只是传播到成员,使它们都成为 int* const
,这仅意味着一旦设置了指针,它们就无法更改。
您可以通过以下方式实现您想要的:
template<typename Type>
struct T {
T(Type* a, Type* b):
a(a), b(b) {}
Type* a;
Type* b;
};
然后:
int a = 1, b = 2;
int const* aRef = &a;
int const* bRef = &b;
T<int const> obj(aRef, bRef);
如果您还希望指针本身是 const
,那么您可以使用:
T<int const> const obj(aRef, bRef);
关于c++ - 从 const 指针创建用户类的 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327723/