在调用模板函数时,我无法从类中传递回调函数。这是一个示例代码:
sortedlist.h
#ifndef _sortedlist_h
#define _sortedlist_h
#include <vector>
template <typename ElemType>
class SortedList {
public:
SortedList(int (*compare)(ElemType a, ElemType b));
~SortedList();
void push(ElemType newElem);
ElemType pop();
private:
std::vector<ElemType> v;
int (*cmp) (ElemType first, ElemType second);
void Sort();
};
template <typename ElemType>
SortedList<ElemType>::SortedList(int (*compare)(ElemType a, ElemType b)) {
cmp = compare;
}
template <typename ElemType>
SortedList<ElemType>::~SortedList() {
}
template <typename ElemType>
void SortedList<ElemType>::push(ElemType newElem) {
v.push_back(newElem);
Sort();
}
template <typename ElemType>
ElemType SortedList<ElemType>::pop() {
ElemType next = v.back();
v.pop_back();
return next;
}
template <typename ElemType>
void SortedList<ElemType>::Sort() {
for (int i=v.size()-1; i>0; i--) {
if(cmp(v[i], v[i-1]) < 0) { //compare function
ElemType temp = v[i];
v[i] = v[i-1];
v[i-1] = temp;
}
else return;
}
}
#endif
game.h
#ifndef _game_h
#define _game_h
#include <string>
#include "sortedlist.h"
class Game {
public:
Game() {};
~Game() {};
void addPlayer(std::string name, int score);
std::string getWinner();
struct Player {
std::string name;
int score;
};
//compare function
int highScore(Player one, Player two);
private:
SortedList<Player> list(highScore);
};
#endif
game.cpp
#include "game.h"
void Game::addPlayer(std::string name, int score) {
Player newEntry;
newEntry.name = name;
newEntry.score = score;
list.push(newEntry);
}
std::string Game::getWinner() {
return list.pop().name;
}
//compare function
int Game::highScore(Player one, Player two) {
if (one.score == two.score) return 0;
if (one.score > two.score) return 1;
return -1;
}
示例主要:
#include <iostream>
#include "game.h"
using namespace std;
int main () {
Game pacman;
pacman.addPlayer("Beavis", 100);
pacman.addPlayer("Butthead", 200);
cout << pacman.getWinner() << endl;
}
当我在XCode上编译它时,我得到“'highscore'不是类型”错误。我也尝试在类外移动Player和highScore,但结果相似。我该怎么做呢?
答案 0 :(得分:4)
在C ++中,您无法就地初始化类成员。您需要在构造函数初始化列表
中执行此操作class Game {
public:
Game():list(highScore) {};
~Game() {};
//compare function
static int highScore(Player one, Player two);
private:
SortedList<Player> list;
};
该函数需要在类定义中声明为static
,因为SortedList
在没有*this
指针的情况下调用它,就像普通函数一样。
比较函数的性能实际上是不必要的,因为在将它们作为参数传递时,总是复制要比较的两个项目。最好使比较函数的类型接收const引用并适当地更改highScore
的签名
int (*compare)(ElemType const& a, ElemType const& b);