c++ - 从 const 指针创建用户类的 const 对象

标签 c++ pointers constants

是否可以强制编译器在我的类中传播常量限定符,以便为构造函数提供常量指针?考虑以下代码:

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 对象中的 ab 处的数据类 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* constint 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);

Live demo

如果您还希望指针本身是 const,那么您可以使用:

T<int const> const obj(aRef, bRef);

关于c++ - 从 const 指针创建用户类的 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327723/

相关文章:

c++ - Visual Studio : Copying content during build, 无论 cpp 更改如何

c++ - 操作系统是否锁定计算机内的全部内存

c - 访问全局整数数组时出现段错误

c++ - 如何使用类的常量裁判和非常量裁判版本避免 DRY?

c++ - 如何将 char 数组定义为常量?

c++ - 使用 const 字符串时创建默认构造函数

c++ - 用 C++ 迭代二维 vector

c++ - std::function/bind 就像没有标准 C++ 库的类型删除

c++ - 使用 new 运算符初始化指向 const float 等的指针

php - 在php中访问<<<HTML中定义的变量