先前声明的c++函数

C++ function previously declared

本文关键字:c++ 函数 声明      更新时间:2023-10-16

我正在为课程作业制作一个战舰程序,我正在调试玩家的部署,我遇到了一个错误,我无法找到解决方案,这是:

bb.cpp:12: error: previous declaration of ‘int vert(int*, std::string)’

我已经在我的代码中搜索了任何先前对int转换的引用,但没有找到任何内容。

下面是函数原型

//game function prototypes
int deploy();  
int firing();  
int gridupdte();  
int win = 0;  
int vert(int *x, string sa);  
int hor(int *y, string s);  
int check();  

函数vert:

int vert(*shipx, shiptype) //Calculates where the bow of the ship should be (the pointy bit)  
{  
    int shiplen;  
    int bow;
    switch(shiptype) // Determines the length to add to the y co-ordinate
    {
        case "cv" : shiplen = 5; break;
        case "ca" : shiplen = 4; break;
        case "dd" : shiplen = 3; break;
        case "ss" : shiplen = 3; break;
        case "ms" : shiplen = 2; break;
    }
    bow = *shipx + shiplen;
    *shipx = bow;
    return *shipx;
}
int hor (*shipy, shiptype) //Calculates where the bow of the ship should be (the pointy bit)
{
    int shiplen;
    int bow;
    switch(shiptype) // Determines the length to add to the x co-ordinate
    {
        case "cv" : shiplen = 5; break;
        case "ca" : shiplen = 4; break;
        case "dd" : shiplen = 3; break;
        case "ss" : shiplen = 3; break;
        case "ms" : shiplen = 2; break;
    }
    bow = *shipy + shiplen;
    *shipy = bow;
    return *shipy;
}

我知道在整个代码的编译中还有其他错误

int vert(*shipx, shiptype) { .. }没有告诉参数的类型。

您没有告诉我们完整的错误(跨越多行),但我怀疑它表示前面的声明的定义不匹配。

写:

int vert(int* shipx, string shiptype) { .. }

您需要在函数定义中包含参数的类型和名称:

int vert (int *shipx, string shiptype) {
...
}

您还应该使原型和定义之间的参数名称匹配

int vert(int *shipx, std::string shiptype)应该是第三个灰框中定义的样子,也更改hor

这篇文章并没有真正解决你所引用的错误。但是你的代码还有一个问题,我想指出,并建议你解决这个问题。

在c++中,switch-case只能是整型常量,不能是字符串字面值。

所以这是错误的:

switch(shiptype) // Determines the length to add to the x co-ordinate
{
    case "cv" : shiplen = 5; break;
    case "ca" : shiplen = 4; break;
    case "dd" : shiplen = 3; break;
    case "ss" : shiplen = 3; break;
    case "ms" : shiplen = 2; break;
}

无法编译

我建议您定义一个enum ShipType,如:

enum ShipType
{
    cv,
    ca,
    dd,
    ss,
    ms
};

然后声明shiptypeShipType类型,这样你就可以这样写:

switch(shiptype) // Determines the length to add to the x co-ordinate
{
    case cv : shiplen = 5; break;
    case ca : shiplen = 4; break;
    case dd : shiplen = 3; break;
    case ss : shiplen = 3; break;
    case ms : shiplen = 2; break;
}