const char *赋值为char的不兼容类型

时间:2014-01-30 21:05:58

标签: c++ class

所以我尝试构建这个程序,它将需要两个 char 和一个 double 。一旦用户输入了信息。我将使用下面的函数将信息传输到对象。 但每次我尝试编译时,我都会在const char *赋值给char [20] 时遇到此错误不兼容的类型。任何人都可以帮助我并澄清何时我不理解。提前谢谢。

void Molecule::set(const char* sym, const char* type, double weighT);

这就是我的称呼方式。

molecule[i].set(symbol, description,weight);

在set()函数中,我只需要将我的私有成员中的值传递给我的对象,我使用 this-> 函数。

////所以这部分应该将值传递给我的Class Molecule私人成员////

this->symbol_ = sym;
this->type_ = type;      
this->weight_ = weighT;

///////这是我的班级分子////////

class Molecule{
private:
    char symbol_[20];
    char type_[20];
    double weight_;
public:
    void set(const char* sym, const char* type, double weighT);
    void display() const;
};

4 个答案:

答案 0 :(得分:3)

您需要使用strcpy或类似内容将char *中的字符串复制到您班级的char []。使用=试图复制指针,但它们确实是不兼容的类型。

答案 1 :(得分:0)

symbol_是一个char [],你需要使用stcpy来填充它。 在set方法中:

   this->symbol_ = sym;

应该成为

  stncpy(this->symbol_, sym, 20);

或者更简单地将symbol_定义为std :: string替换:

  char symbol_[20];

  std::string symbol_;

答案 2 :(得分:0)

此代码

this->symbol_ = sym;
this->type_ = type;      

无效。数组没有复制赋值运算符。您应该使用标头<cstring>

中声明的标准C函数strcpy或strncpy

例如

std::strncpy( this->symbol, sym, 20 );
this->symbol[19] = '\0';
std::strncpy( this->type, type, 20 );      
this->type[19] = '\0';

同样最好使用枚举器或静态常量为幻数20指定名称。

也可以使用标准类std :: string代替字符数组,该类具有多个重载的赋值运算符。

答案 3 :(得分:0)

指针和数组不是一回事,尽管很容易相信它们是。 由于指针衰减,数组可以作为参数传递给请求指针的函数,这可以使人们相信它们是可互换的。

请参阅此文章:What is array decaying?

当您声明symbol_[20]时,这会告诉类在创建对象时分配20个字节。 symbol_始终指向此分配。你不能用指针重新分配它。

您可能希望使用sym复制std::strncpy指向的文字。但要小心。如果sym指向的字符串大于19个字符(末尾为空字符为19 + 1),则需要手动终止带有空字符(\ 0)的symbol_数组。是一个有效的字符串。

#include <cstring>
...
std::strncpy(symbol_, sym, sizeof(symbol));
symbol_[19] = '\0';

我没有机会编译上面的代码,因此,最好先研究一下本文末尾的示例: http://www.cplusplus.com/reference/cstring/strncpy/?kw=strncpy