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

C++引入.h头文件到main.cpp编译报构造析构未定义错误如何解决

C++宠物信息管理代码编译错误修复方案

错误原因

你遇到的是链接阶段报错,根本原因有两个:

  1. 你在dog_list类中声明了构造函数dog_list()和析构函数~dog_list(),但没有提供对应的实现代码,链接器找不到函数定义
  2. 头文件中存在不合理的全局对象定义、冗余声明,同时代码逻辑存在数组越界、计数器失效的隐藏问题

具体修复步骤

  • 给头文件添加头文件守卫,避免多文件编译时重复包含报错
  • 补全dog_list类的构造、析构函数空实现(当前类无需要手动管理的资源,空实现即可满足需求)
  • 将头文件中的全局对象op的定义移到main.cpp中,避免多个文件引入头文件时出现重复定义错误
  • 删除头文件末尾多余的全局函数声明void record_pets();,该声明与类的成员函数冲突且无意义
  • 修正成员函数record_pets中的成员访问逻辑:类的成员函数可以直接访问自身的成员变量,不需要加全局对象op.前缀
  • 修正cin.get的读取长度参数,从硬编码的25改为宏定义SIZE,避免超过数组长度导致内存越界
  • 调整计数器i的自增逻辑,将++i移到do-while循环内部,避免计数器失效导致无限循环
  • 修正循环末尾多余的独立大括号,保证逻辑正确

修正后完整代码

program3.h

#ifndef PROGRAM3_H
#define PROGRAM3_H
#include<iostream>
#include<cstring>
#include<cctype>
#include<fstream>
using namespace std;
const int SIZE = 20;
const int END = 11;
class dog_list
{
    public:
    dog_list();
    ~dog_list();
    void record_pets();
    private:
    char name[SIZE];
    char breed[SIZE];
    char species[SIZE];
    char service[SIZE];
    char special[SIZE];
};
#endif

main.cpp

#include "program3.h"
dog_list op;

int main()
{
    op.record_pets();
    return 0;
}

dog_list::dog_list() {}
dog_list::~dog_list() {}

void dog_list::record_pets()
{
    char personal_list[SIZE];
    int i = 0;
    char again;

    do
    {
        cout << "Enter in pets name: ";
        cin.get(name,SIZE,'\n');
        cin.ignore(100,'\n');   
        cout << endl << "Enter breed of pet:  ";
        cin.get(breed, SIZE, '\n');
        cin.ignore(100,'\n');
        cout << endl << "Enter species: ";
        cin.get(species,SIZE,'\n');
        cin.ignore(100,'\n');
        cout << endl <<  "Enter in service qualifications: ";
        cin.get(service,SIZE,'\n');
        cin.ignore(100,'\n');
        cout << endl << "Enter in special notes: ";
        cin.get(special,SIZE,'\n');
        cin.ignore(100,'\n');
        cout << endl;

        cout << "Name:  " << name << endl;
        cout <<"Breed: " <<  breed << endl;
        cout << "Species: " << species << endl;
        cout << "Service Qualifications: " << service << endl;
        cout << "Special Notes: " << special << endl;

        cout << "Pet saved! Would you like to enter another pet? Y/N: " << endl;
        cin >> again;
        cin.ignore(100,'\n');
        cout << endl;

        if(again == 'y')
        {
            again = toupper(again);
        }
        ++i;
    }while(again == 'Y' && i <= END);
}

编译运行命令

使用如下命令即可编译运行:

g++ main.cpp -o pet_record
./pet_record

修复后代码可以正常输入宠物信息,打印输入的内容,最多支持输入12条宠物信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:45:00