不推荐使用字符串文字到char

时间:2014-03-16 19:44:17

标签: c++ string function char

有没有办法摆脱3个警告: “从字符串文字转换为'char *'已弃用”

这些是我的形状构造。它们是来自shapes基类的派生类。

我收到了这3行的警告。

right_triangle right_triangle("RIGHT-TRIANGLE-1", 5.99, 11.99);
square         square        ("SQUARE-1", 11.99);
rectangle      rectangle     ("RECTANGLE-1", 11.99, 5.99);

由于所有3个类基本上都做同样的事情,我将使用right_triangle对象作为例子。在构造函数中,创建了有关形状的所有内容。

这是班级。

class right_triangle : public shapes
{
   char  *p_name;
   float base,
         height,
         hypotenuse;
public:
   void  show_shape     ();
         right_triangle (char name[17], float base, float height);
         ~right_triangle()                          {}

};

这是构造函数。

//**********************************************************************
//*                     Right triangle constructor                     *
//**********************************************************************
right_triangle::right_triangle(char name[17], float rt_base, float rt_height)
{
   // Print constructor lines
   cout << "\n\n\nCreating right triangle shape";
   cout << "\n     with base = " << rt_base
        << " and height = "      << rt_height;

   // Cause pointer to point to dinamically allocated memory
   if((p_name = (char *)malloc(strlen(name)+1)) == NULL)
     fatal_error(1);
   else
   {
   strncpy(p_name, name, strlen(name)+1);
   base       = rt_base;
   height     = rt_height;
   set_total_sides (3);
   set_unique_sides(3);
   hypotenuse = hypot(base, height);
   set_area        (0.5f * base * height);
   set_perimeter   (base + height + hypotenuse);
   }

}

有没有办法摆脱这些警告?我正在使用char数组,因为strcpy我必须得到形状的名称。任何帮助或建议将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:5)

停止将字符串存储为C字符串。使用std::string

如果您确实需要C字符串,则需要存储const char*(不能修改文字)。但你不是。

答案 1 :(得分:2)

只需更改构造函数的声明

即可
right_triangle (char name[17], float base, float height);

right_triangle( const char name[17], float base, float height );

在C ++中,字符串文字的类型为const char []。

考虑到这些声明是等效的并且声明了相同的函数

right_triangle( const char name[17], float base, float height );
right_triangle( const char name[], float base, float height );
right_triangle( const char *name, float base, float height );

还使用运算符new代替C函数malloc

   p_name = new char[strlen( name ) + 1];
   strcpy( p_name, name );

同样,析构函数无效

 ~right_triangle() {}

必须为p_name释放已分配的内存。

 ~right_triangle() { delete [] p_name; }

还要将复制构造函数和复制赋值运算符定义为已删除或明确定义它们。

答案 2 :(得分:0)

首先请注意,在函数声明中char name[17]只是char*的精彩拼写。其次,字符串文字的类型是char const[N],具有合适的N。这些数组很高兴地转换为char const*转换为char*,因为后者失去了常量(并且使用C ++ 11,根据该转换,根本不支持此转换。尽管可能有些编译器会继续允许转换为char*)。

相关问题