简体   繁体   中英

How can I pass values from an array to the constructor? C++

I've created a program that reads in data from a file and creates objects from them. However their values can vary and thus I made an array that can expand to a definite amount. When I try to pass said through the constructor I run into some trouble. Also I'm not supposed to use vectors which from what I understand would have made this a lot easier.

                    //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. 

This is the cpp file it calls on create the object

#include "Vhs.cpp"


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


Vhs::~Vhs(void)
{
}   

and this it it's .h file

#pragma once
class Vhs
{

public:

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


};  

all the variables exist, i just removed all the declarations to make things look cleaner. Thanks for any help

You can pass a C-array like this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM