我正在嘗試通過給定的教程學習 C 。
我試著寫一些代碼。Visual Studio 說,沒有錯誤,但是當我嘗試開始除錯時,它不起作用。有人能幫我嗎。
我正在拋出以下例外。
這是錯誤訊息:
https://prnt.sc/1x6qqgc
#include <iostream>
#include <string>
using namespace std;
class Question
{
private:
string text;
string choices[3];
string answer;
public:
Question(string text, const string choices[3], string answer)
{
this->text = text;
this->choices[3] = choices[3];
this->answer = answer;
}
bool checkAnswer(string answer)
{
return this->answer == answer;
}
string getText()
{
return this->text;
};
};
class Quizz
{
private:
Question* questions[5];
int score = 0;
int questionIdx = 0;
public:
Quizz(Question questions)
{
this->questions[5] = &questions;
};
Question* getQuestions()
{
return questions[questionIdx];
};
void displayQuestion()
{
Question* questions = getQuestions();
cout << questionIdx 1 << " / " << 5 << "Question : " << questions->getText();
};
};
int main()
{
const string cho[3] = { "Carl","Mike","Jason" };
Question q1 = {"Who has a dog?", cho, "Carl"};
Question q2 = { "Who has a cat", cho , "Mike" };
Question q3 = { "Who knows i have a cat ", cho , "Mike" };
Question q4 = { "Who knows i haven't got a dog", cho , "Carl" };
Question q5 = { "Who knows i live in LA", cho , "Jason" };
Question questions[5] = { q1,q2,q3,q4,q5 };
Quizz quiz(questions[5]);
quiz.displayQuestion();
return 0;
}
uj5u.com熱心網友回復:
您可以在任何地方進行陣列外訪問:
this->choices[3] = choices[3]; --> You can only access up to choices[2]
this->questions[5] = &questions; --> You can only access up to questions[4]
Quizz quiz(questions[5]);
注意:從索引 0 開始在陣列中計數意味著如果您定義string choices[3];這意味著您在choices[0], choices[1]&處有 3 個字串choices[2]
uj5u.com熱心網友回復:
已解決,謝謝您的幫助。
#include <iostream>
#include <string>
using namespace std;
class Question
{
private:
string text;
string choices[3];
string answer;
public:
Question(string textt, string choices[] , string answerr)
{
text = textt;
for (int i = 0; i < 3 ; i ) {
this->choices[i] = choices[i];
}
answer = answerr;
}
bool checkAnswer(string answer)
{
return this->answer == answer;
}
string getText()
{
return this->text;
};
};
class Quizz
{
private:
Question* questions[5];
int score = 0;
int questionIdx = 0;
public:
Quizz(Question questions[])
{
for (int i = 0; i < 5; i )
{
this->questions[i] = &questions[i];
}
};
Question* getQuestions()
{
return questions[questionIdx];
};
void displayQuestion()
{
Question* questions = getQuestions();
cout << questionIdx 1 << " / " << 5 << "Soru : " << questions->getText();
};
};
int main()
{
const string cho[3] = { "Carl","Mike","Jason" };
Question q1 = {"Who has a dog?", cho, "Carl"};
Question q2 = { "Who has a cat", cho , "Mike" };
Question q3 = { "Who knows i have a cat ", cho , "Mike" };
Question q4 = { "Who knows i haven't got a dog", cho , "Carl" };
Question q5 = { "Who knows i live in LA", cho , "Jason" };
Question questions[5] = {q1,q2,q3,q4,q5};
Quizz quiz(questions);
quiz.displayQuestion();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/335273.html
