将vector传递给构造函数

Passing a vector to constructor

本文关键字:构造函数 vector      更新时间:2023-10-16

我是c++新手,我试图在我的程序中实现类。我在java中做过类似的程序。但是我很难在c++中实现类。我想传递一个带有字符串的向量从main到一个叫做Search的类。我可以通过值或引用传递向量。我使用向量*,这意味着得到向量地址。这是别人告诉我的。我不知道该怎么说。我确信我的代码中有更多的错误。请有人帮助我或解释我如何在构造函数中初始化向量以及如何添加值,以便我可以在方法中使用向量??我使用Visual Studio PRO 2010。非常感谢您的回复。

Search.h

// pragma once  
#include "std_lib_facilities.h"  
#include <vector>   
class Search    
{  
public:  
Search();  
    Search(int dd, int mm, int year,vector<string>* dat);  
    vector<string> get_result ();  
    ~Search(void);  
private:     
int d;  
int m;  
int y;  
vector<string> data;   
};     

Search.cpp

#include "Search.h"    
#include <vector>   
#include "std_lib_facilities.h"  
Search::Search()  
:d(1), m(1), y(2000), data(){} //data() is the vector but iam not sure if ihave set the value corectly 
Search::Search(int dd, int mm, int year,vector<string>*dat)    
:d(dd),m(mm),y(year), data(dat){}//no instance of constructor matches   the construcor list -- this is the error iam getting  
//iam trying to initiliaze the varibale data of type vector.But i dont know how to do it.  
Search::~Search(void)  
{    
}  
vector<string> Search::get_result ()  {// implementation where i need to use   the data stored in a vector  
}  
//main program  
   #include "std_lib_facilities.h"   
    #include <string>  
    #include <sstream>  
    #include <stdio.h>  
    #include "Search.h"    
    #include <vector>    
   int main(){    
   int day, month, year;  //iam gonna ask user to input these
    day=20;  
    month=12;  
    year=2014;  
vector<string>flight_info;  
ifstream inputFile("flight.txt");
// test file open   
if (inputFile) {        
 string value;
  // read the elements in the file into a vector    
     while ( inputFile >> value ) {  
   flight_info.push_back(value);//this is the vector i want to pass to class   Search
       }
   }  
   Search search(day,month,year,flight_info)   
    //this where i want to create object of Search class but iam gettin error -no     instance of constructor matches the `enter     code here`construcor list.   
}

这定义了一个vector:

vector<string>flight_info;  

定义了一个vector成员变量:

vector<string> data;

通过将vector传递给构造函数来调用构造函数:

Search search(day,month,year,flight_info)   

但是这个构造函数需要一个指向向量的指针 !

Search(int dd, int mm, int year,vector<string>* dat);  

您不需要通过指针传递任何标准容器(如果您发现自己试图这样做,可能会做错一些事情)。

您可以将构造函数重写为Search(int dd, int mm, int year,vector<string> dat)来解决您的错误。您只需要更改构造函数的原型,因为data(dat)已经正确地构造了成员向量。