问题描述
我试图从一个简单的程序抽象出一个方法。此方法根据预先声明的CAPACITY常量测试数组的长度,如果条件不满足,则会输出错误消息。
I'm trying to abstract out a method from a simple program. This method tests the length of an array against a predeclared CAPACITY constant, and spits out an error message if conditions aren't met. However, I'm having trouble creating a header file with a .cpp file to hold the method.
头文件:
//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;
}
}
运行包含<$ c的main.cpp文件$ c> #includearrayHelper.h错误,字符串未在头文件中声明
。在头文件中包含字符串没有效果,但 #includearrayHelper.cpp
会导致方法的重新定义。我应该如何处理这个问题?
Running this main.cpp file that contains #include "arrayHelper.h"
errors out that string is not declared
in the header file. Including string in the header file has no effect, but #include "arrayHelper.cpp"
results in a redefinition of the method. How should I approach this problem?
推荐答案
您应该 #include< string>
,并将 string
指定为 std :: string
,因为使用命名空间std
在头文件中是一个坏主意。事实上,这是一个坏主意, code> .cpp 太好了。
//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
#include <string>
void arrayLengthCheck(int & length, const int capacity, std::string prompt);
#endif // ARRAYHELPER_H
这篇关于C ++头重定义/声明mixup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!