簡體   English   中英

如何將值從數組傳遞到構造函數? C ++

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

我創建了一個程序,該程序從文件中讀取數據並從中創建對象。 但是它們的值可以變化,因此我制作了一個可以擴展到一定數量的數組。 當我嘗試通過構造函數傳遞說時,我遇到了一些麻煩。 而且我不應該使用矢量,據我所知,矢量將使它變得容易得多。

                    //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);


};  

所有變量都存在,我只是刪除了所有聲明以使事情看起來更整潔。 謝謝你的幫助

您可以像這樣傳遞一個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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM