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

C++模板实现冒泡排序出现undefined reference链接错误如何修复?

报错修复方案

错误原因

你遇到的链接错误是两个问题共同导致的:

  • 模板函数名不匹配:头文件中声明的排序函数名为BubbleSortZ,但BubbleSortZ.cpp中的实现函数名为BubbleSort,名称不一致导致编译器找不到对应实现。
  • 模板函数实现位置错误:C++的模板函数不能把声明和实现拆分到.h和.cpp两个文件中,编译阶段处理模板实例化时,编译器只能看到头文件内容,无法感知到.cpp里的模板实现,就不会生成对应类型的函数实例,链接时自然报未定义引用。

具体修复步骤

  1. 修正模板函数名称:将BubbleSortZ.cpp里的void BubbleSort (std::vector <dataType>& arr)改为void BubbleSortZ (std::vector <dataType>& arr),和头文件声明保持一致。
  2. 迁移模板实现到表头:把整个BubbleSortZ模板函数的代码从BubbleSortZ.cpp剪切到BubbleSortZ.h中,放在Test()函数声明的上方。
  3. 修正注释中的错误参数:如果要测试字符串排序,把注释里的str::str改为std::string即可。

修改后完整代码示例

BubbleSortZ.h

#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>

template <typename dataType>
void BubbleSortZ (std::vector<dataType>& arr) {
    std::cout << "Data items in original order:" << std::endl;
    for (std::size_t i= 0; i < arr.size (); ++i)
    {
        std::cout << std::setw(4) << arr.at (i);          
    }
    std::cout << std::endl;
    
    bool changesMade = true;
    for(std::size_t pass = 0; pass < arr.size() - 1 && changesMade; ++pass) {
        changesMade = false;
        for (std::size_t j = 0; j < arr.size()- 1 - pass; ++j) {
            if (arr.at (j) > arr.at (j + 1)) {
                
                dataType hold = arr.at (j);
                arr.at (j) = arr.at (j+1);
                arr.at (j+1) = hold;
                changesMade = true;
            }
        }
        std::cout << "Data items in pass" << pass + 1 << std::endl;
        for (std::size_t i=0; i<arr.size (); ++i) {
            std::cout << std::setw (4) << arr.at (i);    
        }
        std::cout << std::endl;
     }
     std::cout <<"Data items in ascending order:" << std::endl;
}

void Test();

#endif

BubbleSortZ.cpp

#include "BubbleSortZ.h"
#include <vector>
#include <string>

void Test () {
    std::vector < short > shortArr;
    shortArr.push_back (2);
    shortArr.push_back (6);      
    
    BubbleSortZ (shortArr);

    std::vector <double> doubleArr;
    doubleArr.push_back (2.0);
    doubleArr.push_back (1.5);
    
    BubbleSortZ(doubleArr);
    
    std::vector <std::string> stringArr;
    stringArr.push_back("two");
    stringArr.push_back("four");
    
    BubbleSortZ(stringArr);     
}

主文件无需修改,修改完成后重新编译即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:24:02