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

如何解决Visual Studio 2022中C++代码的LNK2019与LNK1120错误?

解决Visual Studio 2022中果汁机项目的LNK2019/LNK1120链接错误

错误信息

编译《DATA STRUCTURES USING C++ SECOND EDITION》的果汁机项目时,出现以下链接错误:

严重性 代码 描述 项目 文件 行 抑制状态
错误 LNK2019 未解析的外部符号 "public: void __cdecl cashregister::acceptamount(int)" (?acceptamount@cashregister@@QEAAXH@Z) 被引用在函数 "void __cdecl sellproduct(class dispensertype &,class cashregister &)" (?sellproduct@@YAXAEAVdispensertype@@AEAVcashregister@@@Z)  Fruit Juice Machine C:\Users\1\source\repos\Fruit Juice Machine\Fruit Juice Machine\Fruit Juice Machine.obj 1
严重性 代码 描述 项目 文件 行 抑制状态
错误 LNK2019 未解析的外部符号 "public: __cdecl cashregister::cashregister(void)" (??0cashregister@@QEAA@XZ) 被引用在函数 main  Fruit Juice Machine C:\Users\1\source\repos\Fruit Juice Machine\Fruit Juice Machine\Fruit Juice Machine.obj 1
严重性 代码 描述 项目 文件 行 抑制状态
错误 LNK2019 未解析的外部符号 "public: __cdecl dispensertype::dispensertype(int,int)" (??0dispensertype@@QEAA@HH@Z) 被引用在函数 main  Fruit Juice Machine C:\Users\1\source\repos\Fruit Juice Machine\Fruit Juice Machine\Fruit Juice Machine.obj 1
严重性 代码 描述 项目 文件 行 抑制状态
错误 LNK1120 3 个未解析的外部符号  Fruit Juice Machine C:\Users\1\source\repos\Fruit Juice Machine\x64\Debug\Fruit Juice Machine.exe 1

问题原因及解决步骤

1. 检查源文件是否添加到项目

LNK2019错误最常见的原因是类的实现文件(.cpp)未被包含在项目编译范围内:

  • 打开Visual Studio 2022的解决方案资源管理器,确认dispensertype.cpp和cashregister.cpp已在项目中。
  • 如果缺失,右键项目名称 → 添加 → 现有项,选中这两个.cpp文件添加到项目中。

2. 修正dispensertype.cpp中的拼写错误

头文件dispensertype.h中私有成员变量名为numberoftime,但在dispensertype.cpp的实现代码中错误写成了numberoftimes(多一个s),导致声明与实现不匹配,链接器无法找到对应符号。

错误代码片段:

int dispensertype::getnumberoftimes()const {
    return numberoftimes;
}

void dispensertype::makesale() {
    numberoftimes--;
}

修正后代码:

int dispensertype::getnumberoftimes()const {
    return numberoftime;
}

void dispensertype::makesale() {
    numberoftime--;
}

另外,dispensertype.cpp中重复实现了getcost和getnumberoftimes函数(这两个函数已在头文件中做内联实现),建议删除这些重复实现以避免冗余:

// 删除以下重复代码
int dispensertype::getcost() const{
    return cost;
}

int dispensertype::getnumberoftimes()const {
    return numberoftime;
}

3. 重新编译项目

完成上述修改后,执行以下操作:

  • 点击菜单 生成 → 清理解决方案
  • 再点击 生成 → 生成解决方案

此时链接错误应该会被修复,项目可正常编译运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:21:11