【问题标题】:C++ Calling a vector inside a function through a function pointerC++通过函数指针调用函数内部的向量
【发布时间】:2016-06-14 19:07:43
【问题描述】:

在我正在处理的一个程序中,我在 main 中声明了一个向量。我有两个使用向量的函数:一个 int 函数和一个标准的 void 'print' 函数。我试图在 void 函数中使用函数指针(指向 int 函数),但我得到了向量尚未声明的错误,即使它在 main.xml 中也是如此。我尝试在 main 之外声明向量,并且该函数运行良好,但我对将其保留在 main 之外犹豫不决。我想知道当在 main 中声明时,是否有某种方法可以在 void 函数中使用向量。这是我要问的一些示例代码:

// Example program
#include <iostream>
#include <vector>
using namespace std;

int returnSquare(vector<int>& numbers);
void print(int (*squarePtr)(vector<int>&));
int (*squarePtr)(vector<int>&);

int main()
{
   vector<int> v(1);
   squarePtr = &returnSquare;

   for(int i = 0; i < v.size(); i++)
   {
       v.at(i) = i * 25;
       cout << v.at(i) << " ";
   }

   print(squarePtr);

   return 0;
}

int returnSquare(vector<int>& numbers)
{
     int product = 0;
     for(int i = 0; i < numbers.size(); i++)
     {
        product = numbers.at(i) * numbers.at(i);
     }
     return product;
}

void print(int (*squarePtr)(vector<int>&))
{
    int answer = (*squarePtr)(v);
    cout << answer << endl;
}

【问题讨论】:

    标签: c++ pointers vector function-pointers


    【解决方案1】:

    在您的函数print 中,您只有一个参数。要调用平方函数,您需要将向量传递给它,例如:

    void print(int (*squarePtr)(vector<int>&), vector<int> &v)
    {
        int answer = (*squarePtr)(v);
        cout << answer << endl;
    }
    

    没有变量v 在函数内部不可见。调用应如下所示:

        print(squarePtr, v);
    

    不太重要。您在全局定义中使用了两次squarePtr 名称。这不会使您的代码清晰。你最好写:

    void print(int (*workerFuncPtr)(vector<int>&));
    int (*squarePtr)(vector<int>&);
    

    【讨论】:

      【解决方案2】:
      void print (int (*squarePtr)(vector<int>&))
      

      这个参数只接受一个指向你的 square 函数的指针,就是这样。它不包含指向您的v 变量的指针或引用。您的打印函数不知道 v 是什么,除非您将 v 作为参数传递,或者将 v 设为全局变量(这就是您将其移出 main 所做的操作)。

      这样做:

      // Modify your print definition to accept a reference to your vector `v`
      void print(int (*squarePtr)(vector<int>&), vector<int>& v);
      
      // Add `v` as the second argument to your print call
      print(squarePtr, v);
      
      // Modify the definition of your print function to accept a reference to your vector `v`
      void print(int (*squarePtr)(vector<int>&), vector<int>& v)
      {
        ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-01
        • 2020-08-04
        相关资源
        最近更新 更多