如何将数组中的值传递给构造函数? C ++

时间:2012-12-03 01:20:20

标签: c++ arrays constructor

我创建了一个程序,它从文件中读取数据并从中创建对象。但是它们的值可以变化,因此我制作了一个可以扩展到一定数量的数组。当我试图通过构造函数传递时,我遇到了一些麻烦。此外,我不应该使用从我理解的内容会更容易的向量。

                    //bunch of code to read in data from the file similar to this below
        getline (readfile, typea);

                    //code determining what each data type is.          

readMedia >>NSA_Value;
for (int i=0; i<=NSA_Value; i++){
getline(readMedia, supporting_actorsa[i]); //this is the array I'm using that can grow a bit to accommodate.

Vhs initial = Vhs(typea, a, b, c, supporting_actorsa[10]); //the constructor ive removed most of the other things to make it more readable. 

这是它在创建对象时调用的cpp文件

#include "Vhs.cpp"


Vhs::Vhs (string type, string a1, string b1, string c1, supporting_actorsa1[10])
{
}
Vhs::Vhs(void)
{
}


Vhs::~Vhs(void)
{
}   

这就是它的.h文件

#pragma once
class Vhs
{

public:

    Vhs(void);
    Vhs (string type, string A2, string B2, string C3, string supporting_actorsA3[10]);
~Vhs(void);


};  

所有变量都存在,我只是删除了所有声明,使事情看起来更清晰。 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

您可以像这样传递一个C数组:

#include <iostream>
#include <string>
using namespace std;
class Vhs {
public:
    Vhs (string type, string A2, string B2, string C3, 
         string *supporting_actorsA3, int n); 
};  
Vhs::Vhs (string type, string a1, string b1, string c1, 
          string *supporting_actorsa1, int n) {
  for (int i = 0; i < n; i++) {
    cout << supporting_actorsa1[i] << endl;
  }
}

int main()
{
  string supporting_actorsa[1024];
  int num_actors;
  num_actors = 2;
  supporting_actorsa[0] = "1";
  supporting_actorsa[1] = "2";
  Vhs initial = Vhs("typea", "a", "b", "c", supporting_actorsa, 
      num_actors);
    return 0;
}