多重定义,不在标题中?为什么地板还双人间
Multiple definition, not in a header? Why does floor return a double?
我试图只使用静态数组来编程合并排序函数,当然我遇到了一个无法理解的错误。
所以第一个问题是,当我编译我的程序时,它在代码的第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++,因为在编译时无法确定声明数组的长度。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么不;名字在地图上是按顺序排列的吗
- 我的字符计数代码计算错误.为什么
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 为什么 std::unique 不调用 std::sort?
- 既然存在危险,为什么项目要使用-I include开关
- 多重定义,不在标题中?为什么地板还双人间