【发布时间】:2013-11-04 00:34:32
【问题描述】:
由于某种原因,以下代码在 DevC++ 中出现编译器错误:[Error] cannot declare member function 'static double* Sort::bubbleSort(double*, int)' to have static links [-fpermissive]
BubbleSort.cpp:
#include <iostream>
#include "Sort.h"
int main(int argc, char** argv) {
double list[] = {4.0, 4.5, 3.2, 10.3, 2.1, 1.6, 8.3, 3.4, 2.1, 20.1};
int size = 10;
double* sortedList = Sort::bubbleSort(list, size);
return 0;
}
排序.h:
class Sort
{
public:
static double* bubbleSort (double list[], int size);
}
;
排序.cpp:
#include "Sort.h"
#include <algorithm> // std::swap
static double* Sort::bubbleSort (double list[], int size)
{
bool changed = true;
do
{
changed = false;
for (int j = 0; j < size - 1; j++)
{
if (list[j] > list[j +1])
{
std::swap(list[j], list[j + 1]);
changed = true;
}
}
}
while (changed);
return list; // return pointer to list array
}
本质上,我试图在不创建 Sort 对象的情况下调用 bubbleSort 函数。如果我先创建一个对象,代码就可以正常工作。
什么可能导致错误?
感谢您的任何建议。
【问题讨论】:
-
删除原型实现中的静态
-
但是我不需要将函数声明为 static 以便在不创建类对象的情况下使用它吗?
-
static修饰符在 Sort.h 中,但不在 Sort.cpp 中。 -
你为什么要让他成为班级成员? C++ 不是 C# 也不是 Java ...您可以创建独立的函数。
-
@navig8tr 看到这里同样的问题:http://stackoverflow.com/questions/5980520/static-methods-in-c
标签: c++ bubble-sort