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

时间:2017-11-06 03:17:51

标签: c++ class

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

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

上面简化的驱动程序似乎是通过参数将参数传递给类。我的类头文件以下列方式构建。

#ifndef QUESTION_H
#define QUESTION_H
#include <string>
using namespace std;

class Question
{
    public:
        void setStem(string newStem);
        void setAnswers(string newAnswers[]); 
        void setKey(char newKey);
        void display();
        string getStem();
        string getAnswer(int index);
        char getKey();

    private:
        string stem;
        string answers[4];
        char key;

};

#endif // QUESTION_H

如何使用传递给对象的参数在我的类中执行函数?我对这条线如何感到困惑,

Question q2("Which country is home to the Kangaroo?",q2Answers,'D');

有任何方法可以将这些参数推送到函数中。任何对此的见解都将非常感激。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么你就是在询问如何制作构造函数(请参阅评论中的OldProgrammer链接):

你可以在头文件中正确使用它,如下所示:

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

(您可以将const std::string& - 部分想象为stringconst char& - 如果您不知道它们的意思那么只是char,因为它不是很现在很重要。)

或者您可以在单独的.cpp文件中创建它:

Question::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::~Question(){} 

你可能会问为什么我们使用析构函数;这是因为有时在删除对象之前我们需要做些事情。 例如,如果您想要保存某些信息或进行更改,或者更常见的是释放您在创建对象时分配的动态内存。否则你会得到内存泄漏,这很糟糕。

然后你可以构造/创建一个对象:

Question q2("Which country is home to the Kangaroo?",q2Answers,'D');

你也可以“重载”构造函数,即你可以创建它的其他版本。例如,如果您想象构造函数的唯一参数是问题:

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

现在,您可以将字符串或字符数组传递给对象。但是如果你只有一个,你也不能做另一个,所以如果我们只有第一个构造函数,我们就不能传递一个字符数组来做同样的事情。你可以根据自己的喜好制作尽可能多的这些,但这并不一定意味着它更好,因为它有很多构造函数。