"从'char'到'char*'的转换无效

"Invalid conversion from 'char' to 'char*'

本文关键字:char 转换 无效      更新时间:2023-10-16

我最近开始学习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;
};