You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中使用多结构体实现测验程序的函数调用报错问题

问题分析与修正方案

你的代码核心问题是为每个题目创建了独立的结构体类型,但这些结构体结构完全一致,属于重复定义;同时函数参数和调用方式也存在错误,导致编译失败。

具体错误点

  • 重复定义结构体类型:q0、q1是结构完全相同的类型,没必要单独定义,复用同一个结构体模板、创建多个实例即可。
  • 函数参数非法:void quiz(struct q)中的struct q是未定义的类型,编译器无法识别。
  • 函数调用错误:quiz(q0)传递的是结构体类型而非实例,C++中函数不能直接接收类型作为参数,必须传递具体对象。

修正后的代码

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

// 定义统一的题目结构体类型
struct QuizQuestion {
    string question;
    string options[3];
    int correctAnswer;
};

void quiz(const QuizQuestion& q) {
    cout << q.question << endl;
    for (int i = 0; i < 3; i++) {
        cout << i + 1 << ". " << q.options[i] << endl;
    }
    int answer;
    cin >> answer;
    if (answer == q.correctAnswer) {
        cout << "Correct\n" << endl;
    } else {
        cout << "Incorrect\n" << endl;
    }
}

int main() {
    // 创建多个题目实例
    QuizQuestion q0 = {
        "Which sea animal has a horn?",
        {"Dolphin", "Clownfish", "Narwhal"},
        3
    };
    QuizQuestion q1 = {
        "What is the biggest animal in the world?",
        {"Blue Whale", "Elephant", "Great White Shark"},
        1
    };

    quiz(q0);
    quiz(q1);
    return 0;
}

关键修改说明

  1. 统一结构体类型:用QuizQuestion作为所有题目的通用类型,避免重复定义结构相同的类型。
  2. 函数参数修正:使用const QuizQuestion&作为参数,既保证类型合法,又通过引用避免不必要的对象拷贝。
  3. 正确创建实例:在main中创建QuizQuestion类型的具体对象q0、q1,并初始化成员变量。
  4. 修复拼写错误:将原代码中的Inorrect改为Incorrect。

内容的提问来源于stack exchange,提问作者user17081855

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 05:03:21