【问题标题】:Passing a string vector to a function and function prototype issue c++将字符串向量传递给函数和函数原型问题c ++
【发布时间】:2018-01-01 01:48:43
【问题描述】:

在这个例子中,编译器说函数“list”没有定义,尽管我在下面写了一个。如果我将函数定义移到顶部所以没有原型,它编译得很好。

有人能解释一下这里发生了什么吗?

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <vector>

    using namespace std;

    void stuff();
    void list(vector<string> things);

    bool alive = true;

    int main()

    {
       vector<string> things;
       things.push_back("Lots");
       things.push_back("Of");
       things.push_back("Things");

       do
       {
         cout << "What do you want to do?\n\n" << endl;
         string input;
         cin >> input;

         if (input == "stuff")
         {
            stuff();
         }
         if (input == "list")
         {
            list();
         }
       } while (alive);

       return 0;
     }

   void list()
     {
       cout << "The things are:\n\n";
       for (int i = 0; i < things.size(); ++i)
       {
         cout << things[i] << endl;
       }
     }

    void stuff()
     {
       cout << "Some stuff" << endl;
     }

【问题讨论】:

  • error C2660: 'list': function does not take 0 arguments - 这甚至没有“定义”这个词。
  • 好吧,我为不正确的错误道歉。在发布之前我尝试了很多东西,定义错误是最普遍的。我想这次只是碰巧不同,我没有注意到。
  • 您有void list(vector&lt;string&gt; things); 的原型,但没有void list(); 的原型。也许您只需将参数提供给list() 函数调用。

标签: c++ function vector


【解决方案1】:

您的 list function definition 签名与您的 function declaration 不同。函数签名应该相同。你的函数定义签名也应该接受一个参数:

void list(std::vector<string> things)
{
    std::cout << "The things are:\n\n";
    for (int i = 0; i < things.size(); ++i)
    {
        std::cout << things[i] << '\n';
    }
}

在你的程序中你调用函数:

list();

它应该在哪里:

list(things);

【讨论】:

  • 现在编译器说“error C2660: 'list': function does not take 0 arguments”并将调用指向list
  • @MrSteve 我在回答中也提到了这一点。
【解决方案2】:

void list(vector&lt;string&gt; things);void list() 不同。您需要将函数实际定义为 void list(vector&lt;string&gt; things) 而不仅仅是原型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-02
    • 2016-01-17
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多