gpt4 book ai didi

C++ 头文件重新定义/声明混合

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:04 29 4
gpt4 key购买 nike

我试图从一个简单的程序中抽象出一个方法。此方法根据预先声明的 CAPACITY 常量测试数组的长度,如果不满足条件,则吐出一条错误消息。但是,我在使用 .cpp 文件创建头文件来保存该方法时遇到问题。

头文件:

    //arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H

void arrayLengthCheck(int & length, const int capacity, string prompt);

#endif // ARRAYHELPER_H

代码文件:

    //arrayHelper.cpp
#include <iostream>
#include <string>
#include "arrayHelper.h"

using namespace std;

void arrayLengthCheck(int & length, const int capacity, string prompt)
{
// If given length for array is larger than specified capacity...
while (length > capacity)
{
// ...clear the input buffer of errors...
cin.clear();
// ...ignore all inputs in the buffer up to the next newline char...
cin.ignore(INT_MAX, '\n');
// ...display helpful error message and accept a new set of inputs
cout << "List length must be less than " << capacity << ".\n" << prompt;
cin >> length;
}
}

运行这个包含 #include "arrayHelper.h" 的 main.cpp 文件会出错,因为 string is not declared 在头文件中。在头文件中包含字符串没有任何效果,但 #include "arrayHelper.cpp" 导致重新定义该方法。我应该如何解决这个问题?

最佳答案

你应该#include <string>在标题中,并引用 string作为std::string , 自 using namespace std在头文件中将是一个坏主意。事实上它是一个 bad idea in the .cpp too .

//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H

#include <string>

void arrayLengthCheck(int & length, const int capacity, std::string prompt);

#endif // ARRAYHELPER_H

关于C++ 头文件重新定义/声明混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14698205/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com