[英]A value of type “*const char *” cannot be assigned to an entity of type “char *”
[英]A value of type const char* cannot be assigned to an entity of type char*?
我有一个如下所示的类(我删除了无关的项目):
class GL_Texture
{
public:
GL_Texture();
private:
char* fileLocation;
};
它的构造函数如下所示:
GL_Texture::GL_Texture()
{
fileLocation = ""; // error C2440: '=': cannot convert from 'const char [1]' to 'char *'
}
构造函数产生错误error C2440: '=': cannot convert from 'const char [1]' to 'char *'
。 即使我尝试将fileLocation
char* const
,我fileLocation
在该行上收到以下错误
error C2166: l-value specifies const object
如果我无法将字符串文字分配给 char*,并且我无法将fileLocation
限定为指向 const 的指针,那么我应该如何在构造函数中对其进行初始化?
你有几个选择:
首先,大多数人会同意的是在大多数情况下最好的:不要使用char *
,使用std::string
。
其次,改为初始化为nullptr
。
第三: fileLocation = strdup("");
然后在析构函数中清理它。 这是丑陋的。
第四:将其更改为char const *
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.