[英]Why does this code trying to hold an array of function pointer return an error?
我已經看過這個問題了。 這是我收到的錯誤消息:
E0304 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=void (*)(), _Alloc=std::allocator<void (*)()>]" matches the argument list
我的目標是讓所有指針都指向一個向量中的函數,這樣我就可以通過測試不同的排序算法來遍歷它們以獲取各種數據集我的代碼:
#include <iostream>
#include <fstream>
#include <chrono>
using namespace std;
#ifndef Sort_h
#define Sort_h
class Sort : public Algorithm
{
public:
Sort() {
algorithms.push_back((sortalgorithms::bubble));
//algorithms.push_back(&(sortalgorithms::merge));
//algorithms.push_back(&(sortalgorithms::insertion));
}
~Sort();
void load(string);
void execute();
void display();
void stats();
void select(int);
void save();
void configure();
private:
int type = 0;
vector<int> data;
string sortname;
int vecSize = 0;
string fileName;
chrono::duration<double> time;
std::vector<void (*)()> algorithms;
};
#endif
#pragma once
#include "Algorithm.h"
#include <string>
#ifndef algorithm_h
#define algorithm_h
using namespace std;
class Algorithm {
public:
Algorithm() {};
virtual ~Algorithm() {};
virtual void load(string) = 0;
virtual void execute() = 0;
virtual void display() = 0;
virtual void stats() = 0;
virtual void select() = 0;
virtual void save() = 0;
virtual void configure() = 0;
};
#endif algorithm_h
我想從函數指針向量中調用函數。
看來您在這里有兩個錯誤,1) 嘗試添加無效的函數引用和 2) 嘗試添加不同的指針類型
sortalgorithms::bubble
不是有效引用,因為它尚不存在於內存中,它只是一個聲明。 要解決這個問題,你需要先有一個sortalgorithms
的實例,然后傳遞bubble
函數的引用,如下所示:sortalgorithms algorithms;
algorithms.push_back(algorithms.bubble);
或者
auto algorithms = new sortalgorithms();
algorithms.push_back(algorithms->bubble);
bubble
的簽名是void
sortalgorithms::bubble
()
,這也不符合向量中所需的類型void (*)()
,因此由於您使用的是屬於sortalgorithms
類的函數,因此必須將向量聲明為std::vector<void (sortalgorithms::*)()> algorithms
放在一起:
class Sort
{
public:
Sort()
{
algorithms.push_back(sortfunctions.bubble);
}
...
private:
...
std::vector<void (sortalgorithms::*)()> algorithms;
sortalgorithms sortfunctions;
};
編輯
雖然原始答案可能適用,但它不包括其他可能的情況
sortalgorithms::bubble
函數具有向量algorithms
預期之外的簽名,因此,要修復錯誤,您必須確保作為參數傳遞給algorithms.push_back()
所有函數都完成了預期的簽名例如,如果sortalgorithms::bubble
將具有以下簽名:
void bubble(int a, int b)
{
...
}
向量algorithms
應聲明為:
std::vector<void (*)(int, int)> algorithms;
您可以使用這三種情況的任意組合,無論適用於您的情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.