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

C++抽象基类与派生类出现未定义引用错误求助

C++派生类构造函数未定义引用错误解决方法

错误原因

这个undefined reference to Derived::Derived()是链接器报错,不属于代码语法问题。核心原因是链接器在合并编译后的目标文件时,找不到Derived类构造函数的实现代码——本质是你编译时没把Derived.cpp这个源文件包含到编译命令里。你的代码逻辑本身是正确的:基类作为抽象类的声明、派生类对纯虚函数的实现、构造/析构函数的声明与定义匹配度都没问题,问题出在编译环节的文件遗漏。

解决步骤

编译时必须将所有相关的.cpp文件作为参数传入,用clang++的话,正确命令如下:

clang++ main.cpp Base.cpp Derived.cpp -o test_program

如果使用g++,则执行:

g++ main.cpp Base.cpp Derived.cpp -o test_program

执行该命令后,链接器就能找到所有类的实现代码,报错会被修复。

额外检查项

如果执行上述命令后仍有问题,可排查以下两点:

  • 确认Derived.cpp与其他文件在同一目录下,或编译时指定了正确的文件路径
  • 检查Derived.cpp中的构造函数名称是否与类名完全一致(C++对大小写敏感)

附上你提供的代码供参考:

Base.h

#ifndef BASE_H
#define BASE_H

class Base {
 public:
  virtual void print() = 0;
  Base();
  virtual ~Base();
};

#endif /* BASE_H */

Base.cpp

#include "Base.h"

#include <iostream>
using namespace std;

Base::Base() { cout << "\n Constructor Base class"; }
Base::~Base() { cout << "base destructor called"; }

main.cpp

#include "Base.h"
#include "Derived.h"

int main() {
  Base *bptr = new Derived;  // A pointer object reference the Base class.
  bptr->print();
  delete bptr;  // Delete the pointer object.
}

Derived.h

#ifndef DERIVED_H
#define DERIVED_H

#include "Base.h"

class Derived : public Base {
 public:
  Derived();
  void print();
  ~Derived();
};

#endif /* DERIVED_H */

Derived.cpp

#include "Derived.h"
#include "Base.h"

using namespace std;
#include <iostream>
Derived::Derived() { cout << "\n Constructor Derived class"; }
void Derived::print() { cout << "Derived is printing." << endl; }
Derived::~Derived() { cout << "Derived class Destructor" << endl; }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:21:43