如何通过在C++中创建对象传递参数给类?

如何通过在C++中创建对象传递参数给类?,c++,class,C++,Class,我正在处理我的第一个单独的类文件。我已经得到了一个驱动程序,我不应该改变,我要创建一个类文件运行的驱动程序 #include <iostream> #include <iomanip> using namespace std; #include "Question.h" int main() { string q2Answers [] = {"China","India","Mexico","Australia"}; Question q2("Whic

我正在处理我的第一个单独的类文件。我已经得到了一个驱动程序,我不应该改变,我要创建一个类文件运行的驱动程序

#include <iostream>
#include <iomanip>
using namespace std;

#include "Question.h"

int main()
{
    string q2Answers [] = {"China","India","Mexico","Australia"};
    Question q2("Which country is home to the Kangaroo?",q2Answers,'D');

    q2.display();
    cout << endl;
}

有任何方法可以将这些参数推送到函数中。如果我没有弄错,你是在问如何在你的问题的评论中建立一个构造器,请参阅OldProgrammer的链接:

Question(std::string q){
      this->stem = q;
}
Question(char c[]){
      this->stem = c;
}
您可以在头文件中进行修改,如下所示:

Question(const std::string& theQuestion, 
         const std::string theOptions[], const char& correctAnswer)
{
    this->stem = theQuestion;
    for(int i=0; i<4; i++){
        this->answers[i] = theAnswers[i];
    }
    this->key = correctAnswer;
}
~Question(){} 
//This is called the "Destructor", it is a function called when the object is destroyed
你可能会问为什么我们使用析构函数;这是因为有时候我们需要在移除对象之前做一些事情。 例如,如果您希望保存某些信息或进行更改,或者更常见的情况是释放创建对象时分配的动态内存。否则,就会出现内存泄漏,这是很糟糕的

然后可以构造/创建这样的对象:

Question q2("Which country is home to the Kangaroo?",q2Answers,'D');
您还可以重载构造函数,也就是说,您可以创建它的其他版本。例如,如果您设想构造函数的唯一参数是以下问题:

Question(std::string q){
      this->stem = q;
}
Question(char c[]){
      this->stem = c;
}

现在可以将字符串或字符数组传递给对象。但是如果你只有一个,你也不能做另一个,所以如果我们只有第一个构造函数,我们不能传递一个字符数组来做完全相同的事情。你可以按你喜欢的方式制作很多,但这并不一定意味着它更好,仅仅因为它有很多构造函数。

如果这是对这个所谓的驱动程序的精确表示,那么你应该找到更好的C++老师。如果你不知道名字空间STD使用了什么,我认为最好保持它直到一个更好的C++的抓握。除非这是一个大而严肃的项目。
Question q2("Which country is home to the Kangaroo?",q2Answers,'D');
Question(std::string q){
      this->stem = q;
}
Question(char c[]){
      this->stem = c;
}