簡體   English   中英

C++ 函數指針

[英]Function Pointer for C++

我正在 lippman 的 Essential C++ 上學習 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>* ,您正試圖將其分配給一個vector<int>* ,即 seq_ptr。 將 seq_ptr 更改為const vector<int>*或更改 fiber_seq 的返回類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM