C++ 类型的值不能分配给类型的实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27134801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
a value of type cannot be assigned to an entity of type
提问by Dionysis Nt.
I have a header file in c++ with a namespace and a class in it
我在 C++ 中有一个头文件,其中有一个命名空间和一个类
namespace imaging{
class Image
{
// to index individual channels
protected:
Component * buffer; // Holds the image data
Image(unsigned int width, unsigned int height, const Component * data_ptr, bool interleaved=false);
}
}
when i try to implement the constructor i get an error a value of type cannot be assigned to an entity of type.
当我尝试实现构造函数时,我收到一个错误类型的值无法分配给类型的实体。
#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!!
}
}
回答by Amxx
data_ptr
is as const Component *
while Image::buffer
is a Component *
data_ptr
是作为const Component *
同时Image::buffer
是一个Component *
By affecting the first to the second you would discard the const
. The whole point of this attribute is to protect data and it should be removed by a simple cast.
通过影响第一个到第二个,您将丢弃const
. 此属性的全部意义在于保护数据,应该通过简单的强制转换将其删除。
You could either edite you constructor argument's type to remove the const
or use
您可以编辑构造函数参数的类型以删除const
或使用
buffer=const_cast<Component*>(data_ptr);
In any case, think about the behaviour you want. Is there any sens for the pointer to be const (it's not a ref) ?
无论如何,请考虑您想要的行为。指针是否有任何意义为 const (它不是参考)?