多重定义,不在标题中?为什么地板还双人间

Multiple definition, not in a header? Why does floor return a double?

本文关键字:为什么 人间 定义 标题      更新时间:2023-10-16

我试图只使用静态数组来编程合并排序函数,当然我遇到了一个无法理解的错误。

所以第一个问题是,当我编译我的程序时,它在代码的第9行给了我一个多重定义错误:

#include <cmath>
#include "includesort.h"

/*
Theses fonctions accept only arrays of unsigned short int with a length in unsigned int
*/
unsigned short int* sortByFusion(unsigned short int arr[]) { // HERE !!!!!!!!
    const unsigned int arrSize = sizeof(arr)/sizeof(unsigned short int);
    if (arrSize <= 1) {return arr;}
    /*
    Declarations and initializations of the two half array
    */
    const unsigned int arrLeftSize = static_cast<unsigned int>(floor(arrSize/2));
    const unsigned int arrRightSize = static_cast<unsigned int>(arrSize - arrLeftSize);
    unsigned short int arrLeft[arrLeftSize];
    unsigned short int arrRight[arrRightSize];
    for (unsigned int i = 0; i < arrLeftSize; i ++)
        arrLeft[i] = arr[i];
    for (unsigned int i = 0; i < arrRightSize; i ++)
        arrRight[i] = arr[i + arrLeftSize];
    /*
    Sort the two arrays
    */
    for (unsigned int i = 0; i < arrLeftSize; i ++)
        arrLeft[i] = *(sortByFusion(arrLeft) + i);
    for (unsigned int i = 0; i < arrRightSize; i ++)
        arrRight[i] = *(sortByFusion(arrRight) + i);
    /*
    And fusion them
    */
    unsigned int i(0), j(0);
    for (unsigned int k = 0; k < arrSize; k ++) {
        if (i >= arrLeftSize)           {arr[k] = arrRight[j]; j ++;} //That line
        else if (j >= arrRightSize)     {arr[k] = arrLeft[i]; i ++;}  //And that line are here to avoid segmentation fault
        else {
            if (arrLeft[i] <= arrRight[j]) {arr[k] = arrLeft[i]; i ++;}
            else {arr[k] = arrRight[j]; j ++;}
        }
    }
return arr;
}

我做错了什么?我试着放一些ifndef-define-endif,但它什么也没做。似乎每个人都有一个问题,在这个论坛上,多重定义总是有点不同。

其次,我使用了一些static_cast,但当我们传递double作为参数时,floor为什么会返回double?从逻辑上讲,它应该给我们一个整数(一个数字的底总是一个整数…(?

对于编译器来说,它是GNUGCC,但我不知道如何找到它的版本。我使用代码::块。

这是头文件:

#ifndef SORT_H_INCLUDED
#define SORT_H_INCLUDED
unsigned short int* sortByFusion(unsigned short int arr[]);
#endif // SORT_H_INCLUDED
 const unsigned int arrSize = sizeof(arr)/sizeof(unsigned short int);

这一行没有按预期工作,因为c++没有保留任何关于运行时数组的数组长度的信息,而运行时数组实际上只是指向数组的指针,因此sizeof(arr)返回指针大小的sizeof(unsigned short int*)


至于为什么第9行有错误,我不能不看到标题sort.h就帮你。


//static_cast<unsigned int>(floor(arrSize/2)); // Wrong
arrSize/2; // Right, C++ does floor integer divisions.

unsigned short int arrLeft[arrLeftSize];
unsigned short int arrRight[arrRightSize];

这两行不是有效的C++,因为在编译时无法确定声明数组的长度。