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

Linux下NetBeans IDE8.2中C++类出现undefined reference错误求助

解决C++编译错误:undefined reference to Instrument::Instrument()

你遇到的链接错误是因为只声明了Instrument类的构造函数和虚析构函数,但没有提供实现代码。C++中,如果你在类里声明了函数(比如构造、析构),必须给出对应的定义,否则链接阶段找不到函数体就会报错。

解决方法有两种:

  1. 在类内部直接实现构造和析构函数
    修改后的代码:
#include <iostream>
using namespace std;

class Instrument
{
public:
    // 空实现构造函数
    Instrument() {}
    void MakeSound(){
        cout<<"Instrument plays..."<<endl;
    }
    // 空实现虚析构函数(虚析构必须有实现,哪怕是空的)
    virtual ~Instrument() {}
};

int main(int argc, char** argv)
{
    Instrument inst;
    cout<<"Start"<<endl;
    cout<<"End"<<endl;
    return 0;
}
  1. 在类外部实现构造和析构函数
    修改后的代码:
#include <iostream>
using namespace std;

class Instrument
{
public:
    Instrument();
    void MakeSound(){
        cout<<"Instrument plays..."<<endl;
    }
    virtual ~Instrument();
};

// 类外部定义构造函数
Instrument::Instrument() {}
// 类外部定义虚析构函数
Instrument::~Instrument() {}

int main(int argc, char** argv)
{
    Instrument inst;
    cout<<"Start"<<endl;
    cout<<"End"<<endl;
    return 0;
}

另外补充:你的代码里使用了cout,必须包含<iostream>头文件,并且要么用std::cout,要么添加using namespace std;,否则会出现cout未定义的编译错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:06