您好,我想做一个一行声明,我正在为我的Quiz项目使用QT创建器,我想通过文字数组表示法(JS)传递它,是否还有其他方法可以在一行声明中声明它。

我想这样构造它:

Card c = new Card("Question?", 2, (Answer[]){ "answer 1", 1, "answer 2", 2, "answer 3", 3} );

这是我的课:
class Answer{
private:
    qint8 id;
    QString answer;

public:
    Answer(QString nAnswer, qint8 nId);
    QString getAnswer();
    qint8 getId();

};

class Card
{
private:
    QString question;
    QVector<Answer> answers;
    qint8 solutionId;

public:
    Card(QString nQuestion, qint8 nSolutionId, Answer[] );
    QString getQuestion();
    QVector<Answer> getAnswers();
    // void setSolutionId(qint8 nSolutionId);

};

Answer::Answer(QString nAnswer, qint8 nId)
{
    answer = nAnswer;
    id = nId;
}


Card::Card(QString nQuestion, qint8 nSolutionId, Answer nAnswers[])
{
    question = nQuestion;
    solutionId = nSolutionId;
}

最佳答案

为了使用

Card c = Card("Question?", 2, { {"answer 1", 1}, {"answer 2", 2}, {"answer 3", 3} } );

你需要改变你的
Card(QString nQuestion, qint8 nSolutionId, Answer[] );

构造函数,以QVector<Answer>代替Answer[]。看起来像
Card(QString nQuestion, qint8 nSolutionId, QVector<Answer> nAnswers );

//...

Card(QString nQuestion, qint8 nSolutionId, QVector<Answer> nAnswers ) :
    question(nQuestion),
    answers(nAnswers),
    solutionId(nSolutionId)
{}

之所以可行,是因为QVector<T>具有采用std::initializer_list<T>的构造函数,因此
{ {"answer 1", 1}, {"answer 2", 2}, {"answer 3", 3} }

将转换为std::initializer_list<Answer>以用于初始化answers

关于c++ - C++文字数组表示法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58614816/

10-13 06:58