不能将 "const <Component> *" 类型的值分配给类型 "<Component> *" 的实体

A value of type "const <Component> *" cannot be assigned to an entity of type "<Component> *"

本文关键字:类型 gt Component lt 实体 分配 const 不能      更新时间:2023-10-16

我在C++中有一个头文件,其中包含命名空间和类:

namespace imaging
{
    class Image
    {
    protected:
        Component *buffer; // To index individual channels
        Image(unsigned int width, unsigned int height, const Component *data_ptr, bool interleaved=false); // Holds the image data
    }
}

当我尝试实现构造函数时,出现错误:a value of type "const <Component> *" cannot be assigned to an entity of type "<Component> *"

#include Image.h
namespace imaging 
{
    Image::Image(unsigned int width, unsigned int height, const Component *data_ptr, bool interleaved=false)
    {
        this->height = height;
        this->width = width;
        buffer = data_ptr; // The error is here!
    }
}

data_ptrconst Component *,而Image::bufferComponent *

通过影响第一个到第二个,您将丢弃const。此属性的全部目的是保护数据,应通过简单的强制转换将其删除。

您可以编辑构造函数参数的类型以删除const或使用

buffer=const_cast<Component*>(data_ptr);

无论如何,想想你想要的行为。指针是常量(它不是参考)有什么意义吗?