&引用;从';char';至';字符*'; 我最近开始学习C++,而且我的构造函数遇到了麻烦。我的类文件的简单示例 class Test { private: char *type; public: Test(const char *type); //this is my constructor };

&引用;从';char';至';字符*'; 我最近开始学习C++,而且我的构造函数遇到了麻烦。我的类文件的简单示例 class Test { private: char *type; public: Test(const char *type); //this is my constructor };,c++,constructor,C++,Constructor,现在我在尝试实现构造函数时遇到了一个问题 Test::Test(const char *type){ this-> type = *type; } 我得到了错误:“从‘char’到‘char*’的转换无效。现在我搜索了这个网站和web来寻找解决方案。但是没有找到任何解决我的具体问题的方法。我可以想象解决方案非常简单,但是我的爱人,我想不出来。试试看。” Test::Test(const char *type){ this-> type = type; } 正如erip所说

现在我在尝试实现构造函数时遇到了一个问题

Test::Test(const char *type){

this-> type = *type;

}
我得到了错误:“从‘char’到‘char*’的转换无效。现在我搜索了这个网站和web来寻找解决方案。但是没有找到任何解决我的具体问题的方法。我可以想象解决方案非常简单,但是我的爱人,我想不出来。

试试看。”

Test::Test(const char *type){

this-> type = type;

}
正如erip所说,尝试使用std::string。尽可能多地使用STL。

你的问题:

char *type;
这将
type
声明为指向
char
的指针。它指向一些内存,其中(希望)有一个字符数组,以空字节结尾

Test(const char *type);
这意味着您的类有一个构造函数,它接收指向
const char
的指针

这将分配给您的成员
类型
,即指针
类型
指向不同的内存位置

... = *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;
};
//使用std::string。
#包括
课堂测试{
公众:
测试(const std::string和type):\u type(type){}
私人:
std::string\u类型;
};
如果您坚持使用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;
};
#包括
课堂测试{
公众:
测试(常量字符*类型)
{
//分配内存并*复制*字符串
_类型=新字符[std::strlen(类型)+1];
标准::strcpy(_类型,类型);
}
~Test()
{
//完成后,记得*释放*内存
删除[]_类型;
}
私人:
char*_型;
};

省略取消引用运算符(
*
)并解析
const
-ness,也许做一个缓冲区的副本…回到你正在读的任何书,再次阅读关于解引用操作符
*
,以及它的作用。给定定义
char*type
,一个
*type
的语句就是一个
char
*
解引用指针我说过一次,我已经说过一千次了。只要使用
std::string
。我已经试过了。给出了错误“从'const char*'到'char*'的转换无效”。回答很好,很好地解释了为什么其他“更简单”的解决方案不好+1.
#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;
};