将向量<string>作为函数参数传递时出现问题 C++

Trouble passing vector<string> as function parameter C++

本文关键字:参数传递 问题 函数 C++ lt 向量 string gt      更新时间:2023-10-16

这就是我正在使用的代码。我希望能够将所有输入传递到此函数中,new_flight该函数目前没有其他代码,而是空声明。我正在尝试通过引用传递令牌,但我已经尝试过* &并且仅按值传递令牌,但似乎都没有工作。

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
void new_flight( vector<string> &tokens );
int main( int argc, char *argv[] )
{
    vector<string> tokens;
    cout << "Reservations >> ";
    getline(cin, input);
    istringstream iss( input );
    copy(istream_iterator<string>( iss ),
         istream_iterator<string>(),
         back_inserter<vector<string> > ( tokens ));
    new_flight( tokens );
}

这是编译器告诉我的

Undefined symbols for architecture x86_64:
  "new_flight(std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&)", referenced from:
      _main in ccplPBEo.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

此外,如果我注释掉我实际将令牌传递给new_flight new_flight( tokens )的行,它可以很好地编译。

感谢您的观看

为了存根一个函数,你需要提供一个函数定义,而不是一个函数声明:

void new_flight( vector<string> &tokens ) {
    // Not implemented
}

你得到的不是编译器错误,而是链接器错误,这是由于你的函数new_flight()没有定义。但你似乎意识到了这个事实。如果调用未定义的函数,则不能期望程序正常工作,因此链接器首先拒绝创建它。

您正在声明函数new_flight,但没有定义它,因此链接器无法链接它。 编写实现(如果只是一个存根),它将编译。

不能调用声明。你需要一个定义。编译器应该为此调用生成什么代码?它没有函数的代码。无法编译程序。

正如其他帖子所指出的:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
void new_flight( vector<string> &tokens );
int main( int argc, char *argv[] )
{
   vector<string> tokens;
   cout << "Reservations >> ";
   getline(cin, input);
   istringstream iss( input );
   copy(istream_iterator<string>( iss ),
     istream_iterator<string>(),
     back_inserter<vector<string> > ( tokens ));
   new_flight( tokens );
}
void new_flight( vector<string> &tokens ) 
{
   // implementation
}

因为你实际上是在 main 之后定义功能,所以编译器需要知道函数的存在,因此我们创建了一个定义函数的"原型"void new_flight( vector<string> &tokens );