将向量传递给构造函数

时间:2014-05-14 10:35:39

标签: c++

Iam是C ++的新手,我试图在我的程序中实现类。我在java中做过类似的程序。但我很难在c ++中实现类。我想将一个带有字符串的向量从main传递给一个名为Search的类。我可以通过值或引用传递向量。我使用矢量*,这意味着得到矢量地址。这是我被告知。我不确定我应该如何引用它。我确信我的代码中有更多错误。可以请某人帮助我或解释我如何在构造函数中初始化向量以及如何添加值以便我可以在menthod中使用向量?我使用的是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.   

}

1 个答案:

答案 0 :(得分:0)

这定义了一个向量:

vector<string>flight_info;  

这定义了一个向量成员变量:

vector<string> data;

这通过将向量传递给它来调用构造函数:

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)已经正确构造了成员向量。