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

C++如何正确关联.h头文件与main.cpp 解决编译错误并实现功能

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

核心错误原因

你遇到的编译报错主要由以下几个语法和逻辑问题导致:

  • 构造/析构函数=default的写法或放置位置错误,触发直接调用构造函数的报错
  • 头文件多声明了一个全局的record_pets函数,和类成员函数冲突
  • main函数中未实例化dog_list类的对象就直接调用op.record_pets()
  • 类成员函数record_pets中错误加了op.前缀访问私有成员,成员函数内部可直接访问自身成员
  • 读入字符串时的长度参数超过数组定义的大小,存在越界风险
  • 循环计数变量i的增量逻辑放在循环体外,不会生效

具体修改步骤

  1. 修改program3.h头文件
    • 把构造、析构函数直接在类内声明为default,无需到cpp中额外定义
    • 删除头文件末尾多余的全局void record_pets();声明
  2. 修改main.cpp(原program3.cpp)文件
    • 删掉原来错误的dog_list::dog_list() = default;、dog_list::~dog_list() = default;两行代码
    • main函数开头先实例化dog_list op;对象
    • 去掉record_pets成员函数中所有成员变量前的op.前缀
    • 把所有cin.get的长度参数从25改为SIZE,避免数组越界
    • 把++i的逻辑挪到do-while循环内部

完整修改后代码

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() = default;
    ~dog_list() = default;
    void record_pets();
    private:
    char name[SIZE];
    char breed[SIZE];
    char species[SIZE];
    char service[SIZE];
    char special[SIZE];
};

main.cpp

#include "program3.h"
int main()
{
    dog_list op;
    op.record_pets();
    return 0;
}

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);
}

编译运行方式

使用gcc编译命令即可正常编译运行:
g++ main.cpp -o pet_record && ./pet_record

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:54:04