"从'char'到'char*'的转换无效
"Invalid conversion from 'char' to 'char*'
我最近开始学习C++,但我的构造函数遇到了问题。我的类文件的简单示例
class Test {
private:
char *type;
public:
Test(const char *type); //this is my constructor
};
现在我在尝试实现构造函数时遇到了问题。
Test::Test(const char *type){
this-> type = *type;
}
我收到错误:"从'字符'到'字符*'的转换无效。现在我搜索了这个网站和网络以寻找解决方案。但是没有找到任何针对我的具体问题的东西。我可以想象解决方案很简单,但为了我的爱,我无法弄清楚。
试试
Test::Test(const char *type){
this-> type = type;
}
也正如埃里普所说,尝试使用std::string
.尝试尽可能多地使用 STL。
您的问题:
char *type;
这会将type
声明为指向 char
的指针。它指向一些内存,其中(希望)有一个字符数组,以空字节结尾。
Test(const char *type);
这意味着您的类有一个构造函数,该构造函数接收指向const char
的指针。
this->type = ...
这会分配给您的成员type
,即指针type
指向不同的内存位置。
... = *type;
不幸的是,在参数type
上使用运算符*
意味着您不是在分配指针,而是分配type
指向的第一个字符的值,这当然不是有效的内存添加。
即使省略*
运算符,仍然存在问题:
- 成员
type
是指向char
的指针。 - 参数
type
是指向const char
的指针。
你不能把const
的东西分配给非const
的东西,至少不能没有演员表,你也不应该这样做。
它也是"浅拷贝"的一个例子,即你的类不会有自己的字符串副本,而只有一个指向它无法控制的一些内存的指针。这不是一个好的设计。
总而言之,这里的"解决方案"是:
在C++编程时,请像C++一样执行。
// Use std::string.
#include <string>
class Test {
public:
Test( const std::string & type ) : _type( type ) {}
private:
std::string _type;
};
如果你坚持使用 C 字符串,那看起来有点像这样:
#include <cstring>
class Test {
public:
Test( const char * type )
{
// Assign memory and *copy* the string
_type = new char[ std::strlen( type ) + 1 ];
std::strcpy( _type, type );
}
~Test()
{
// Remember to *release* the memory when you are done
delete [] _type;
}
private:
char * _type;
};
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将函数参数"const char*"转换为"std::string_view"是
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 如何在虚幻引擎4中将char*转换为TCHAR?
- C++:将模板类型 char 转换为 std::string
- strcmp/char* 转换无法按预期工作
- C++中的SQLite char*转换
- 无法从 const char* 转换为 const char *&
- 在 C++ 中将 char 转换为 int,而无需符号位传播
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 试图使用strCMP时的char转换错误
- 无法从'const char *'转换为'LPCTSTR'
- 将 std::vector<char> 转换为字符* 会导致字符缺陷
- 使用 static_cast 将 char 转换为 int c++
- 如何在 C++(MFC) 中将 char* 转换为 LPCTSTR
- 无法将const char转换为字符串构造字符串