我正在处理我的第一个单独的类文件。我已经获得了一个我不应该更改的驱动程序,我将创建一个运行驱动程序的类文件。
#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');
可以通过任何方式将这些参数推送到函数中。对此有任何见解将不胜感激。
最佳答案
如果我没理解错的话,你是在询问如何制作构造函数(请参阅 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&
部分想象成 string
或将 const 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;
}
现在您可以将字符串或字符数组传递给对象。但是如果你只有一个,你就不能做另一个,所以如果我们只有第一个构造函数,我们就不能传递一个字符数组来做同样的事情。您可以根据需要制作任意数量的此类内容,但这并不一定意味着它具有大量构造函数就更好。
关于c++ - 如何通过在 C++ 中创建对象来将参数传递给类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47129246/