【问题标题】:String literal to char is deprecated不推荐使用 char 的字符串文字
【发布时间】:2014-04-21 22:12:33
【问题描述】:

有什么办法可以摆脱 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 我必须获取形状的名称。任何帮助或建议将不胜感激,谢谢。

【问题讨论】:

  • 您的问题右侧的相关部分中似乎已经存在许多重复的问题。

标签: c++ string function char


【解决方案1】:

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

如果你真的需要一个 C 字符串,你应该存储一个 const char*(文字不能被修改)。但你没有。

【讨论】:

  • 作为奖励,您将摆脱凌乱的 malloc 和 strncpy。
【解决方案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; }

还可以将复制构造函数和复制赋值运算符定义为已删除或显式定义。

【讨论】:

  • 感谢您的帮助,这正是我想要的!
【解决方案3】:

首先,请注意在函数声明中char name[17] 只是char* 的一个奇特拼写。其次,字符串字面量的类型是char const[N] 和一个合适的N。这些数组很高兴地转换为char const*,但 not 转换为 char*,因为后者失去了 constness(根据标准,C++11 根本不支持这种转换,尽管可能有些编译器会继续允许转换为char*)。

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 2012-11-21
    • 2020-09-30
    • 2018-11-03
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2011-12-28
    相关资源
    最近更新 更多