【发布时间】: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 我必须获取形状的名称。任何帮助或建议将不胜感激,谢谢。
【问题讨论】:
-
您的问题右侧的相关部分中似乎已经存在许多重复的问题。