【问题标题】:How can I pass values from an array to the constructor? C++如何将值从数组传递给构造函数? C++
【发布时间】:2012-12-03 01:20:20
【问题描述】:

我创建了一个程序,它从文件中读取数据并从中创建对象。但是它们的值可能会有所不同,因此我制作了一个可以扩展到一定数量的数组。当我尝试通过构造函数传递 say 时,我遇到了一些麻烦。另外,我不应该使用向量,据我所知,这会使这变得容易得多。

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


};  

所有变量都存在,我只是删除了所有声明以使事情看起来更干净。 感谢您的帮助

【问题讨论】:

  • “当我试图通过构造函数传递说时,我遇到了一些麻烦” - 定义“麻烦”。细节很重要。
  • 为什么不能使用向量?这将使整个情况变得微不足道:)
  • 那里有一个问题,在某个地方,我知道是的,但可惜我没有把握。
  • 对不起!当我尝试运行我的程序时,它会告诉我在我编写它的方式中没有 Vhs 的 Constructor 实例,或者它的类型错误。我现在根据下面有人说的再次编辑它。如果它仍然不起作用,我会尝试让我的问题更清楚
  • "所有变量都存在,我只是删除了所有声明以使事情看起来更干净。"不,实际上,不包含细节的代码不会让事情变得更干净。你应该意识到你不知道什么是重要的或不重要的。创建一个自包含的小示例来演示您的问题 - 删除不需要显示您的问题的部分,但保留使您的程序编译所需的所有内容。您应该能够将其复制粘贴到 ideone.com 并进行编译(或者以您感到困惑的方式失败)。我敢打赌你还有其他问题。

标签: c++ arrays constructor


【解决方案1】:

你可以像这样传递一个 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;
}

【讨论】:

  • 谢谢,如果我遇到问题,我会试试看。感谢您的快速回复!
  • 我想当他说他不能使用向量时,他的意思是他根本不能使用它们,而不仅仅是他的构造函数。不过,矢量肯定会让事情变得更容易。
  • 是的,我根本不能使用向量:/ 我遗漏了向量的东西并编译了它,但我不确定这是否意味着我以后会遇到问题。跨度>
  • 非常感谢!我通过将所有内容扫描到字符串变量并附加它来找到解决方法。我知道这不是一个好主意,但我不需要单独编辑它们,所以应该没问题。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2018-05-09
  • 2012-03-14
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 2023-03-06
相关资源
最近更新 更多