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

C++传递vector<vector<char>>参数时出现未定义引用错误求助

问题解决:undefined reference 错误分析与修复

核心错误原因

undefined reference 错误的直接原因是函数声明和定义的签名不匹配:

  • 声明的drawfield是传值参数:void drawfield(std::vector <std::vector <char>>);
  • 实际定义的drawfield是const引用参数:void drawfield( const std::vector<std::vector <char>> &playfield )

编译器在链接阶段找不到声明对应的函数实现,因此抛出该错误。

完整修复后的代码

#include <iostream>
#include <vector>

// 修正函数声明,与定义保持一致
void drawfield(const std::vector<std::vector<char>>&);
void round(int&);
int roundnumber = 1;

int main()
{
    std::vector<std::vector<char>> playfield 
    { {'1','2','3'},{'4','5','6'},{'7','8','9'} };
    drawfield(playfield);
    // 修正:调用round函数,而非声明变量
    round(roundnumber);
    // 修正拼写错误:pause而非puase
    system("pause");
    return 0;
}

// 修正:声明与定义的参数类型一致(int&)
void round(int &roundnumber)
{
    roundnumber++;
}

void playerinput(std::vector<std::vector<char>> &playfield)
{
    // 移除无效代码:playfield[3][3]会触发数组越界(索引从0开始,最大为2)
    int input = 0;
    int ir = 0;   // 输入对应的行索引
    int ic = 0; // 输入对应的列索引
    std::cout << "wähle ein freies Feld von 1-9 in dem du setzten Möchtest:";
    std::cin >> input;
    // 修正索引计算:输入1-9需先减1,才能对应0-2的合法索引
    input--;
    ir = input / 3;
    ic = input % 3;   
    
    if(roundnumber % 2 == 0)
    {
        playfield[ir][ic] = 'X';
    }
    else 
    {
        playfield[ir][ic] = 'O';
    }
}

void drawfield(const std::vector<std::vector<char>> &playfield )
{
    // 移除无效代码:playfield[3][3]越界
    // 修正循环条件:r < playfield.size(),避免无限循环
    for (int r = 0; r < playfield.size(); r++)
    {   
        for (int c = 0; c < playfield[r].size(); c++)
        {
            std::cout << " " << playfield[r][c] << " ";
        }
        std::cout << std::endl;
    }   
}

其他关键修复点

  • round函数签名不匹配:原声明为void round(int);,定义是void round(int &roundumber),修正声明为void round(int&);
  • main函数逻辑错误:int round (roundnumber);是声明变量而非调用函数,改为round(roundnumber);
  • 数组越界问题:删除playfield[3][3]这类无效代码;输入处理时先将输入值减1,避免索引超出vector范围
  • 循环条件错误:原for (int r = 0; playfield.size(); r++)会导致无限循环,改为r < playfield.size()
  • 拼写错误:system("puase");修正为system("pause");

内容的提问来源于stack exchange,提问作者Käsekuchen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:40:16