用于C++的函数指针
Function Pointer for C++
我正在研究C++ lippman 的 Essential C++。这是一些代码,其中两行包含错误,而我不知道为什么会发生错误以及如何修复它。
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
const vector<int>* fibon_seq(int size) {
const int max_size = 1024;
static vector<int> elems;
if (size <= 0 || size > max_size) {
cerr << "Error";
return 0;
}
for (int ix = elems.size(); ix < size; ++ix) {
if (ix == 0 || ix == 1)
elems.push_back(1);
else elems.push_back(elems[ix - 1] + elems[ix - 2]);
}
return &elems;
}
void display(const vector<int>* vec, ostream &os = cout) {
if (!vec)
cerr << "null vector";
for (int i = 0; i < (vec)->size(); ++i)
os << (*vec)[i] << " ";
os << endl;
}
bool fibon_elem(int pos, int &elem, const vector<int>* (*seq_ptr)(int)) {
const vector<int> *pseq = seq_ptr(pos);
if (!pseq){
elem = 0; return false;
}
elem = (*pseq)[pos - 1];
return true;
}
int main()
{
const vector<int>* (*(*seq_array)[1])(int);
(*seq_array)[0] = fibon_seq;
vector<int>* (*seq_ptr)(int);
int seq_index = 0;
seq_ptr = (*seq_array)[0];//This is the line with error.
//(a value of type "const std::vector<int, std::allocator<int>> *(*)(int)"
//cannot be assigned to an entity of type "std::vector<int, std::allocator<int>>
//*(*)(int)"
//C2440 '=': cannot convert from 'const std::vector<int,std::allocator<_Ty>>
//*(__cdecl *)(int)' to 'std::vector<int,std::allocator<_Ty>>
//*(__cdecl *)(int)'
int a;
fibon_elem(12, a, seq_ptr);//This is the line with error.
//argument of type "std::vector<int, std::allocator<int>> *(*)(int)"
//is incompatible with parameter of type "const std::vector<int, std::allocator<int>>
//*(*)(int)"
//C2664 'bool fibon_elem(int,int &,const std::vector<int,std::allocator<_Ty>>
//*(__cdecl *)(int))': cannot convert argument 3 from 'std::vector<int,std::allocator<_Ty>>
//*(__cdecl *)(int)' to 'const std::vector<int,std::allocator<_Ty>>
//*(__cdecl *)(int)' test
getchar();
return 0;
}
对于错误的第一行,我使等式的两边具有相同的类型,而编译器说无法分配值。对于错误的第二行,两个相同的类型彼此不兼容。
编译器给出的错误消息如下:
你的函数fibon_seq返回一个const vector<int>*
,你试图把它分配给一个seq_ptr vector<int>*
。 将seq_ptr更改为const vector<int>*
或更改fiber_seq的返回类型。
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址