用于C++的函数指针

Function Pointer for C++

本文关键字:指针 函数 C++ 用于      更新时间:2023-10-16

我正在研究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的返回类型。