Bra*_*ice 0 c++ include header-files
我试图从一个简单的程序中抽象出一个方法.此方法针对预先声明的CAPACITY常量测试数组的长度,并在不满足条件时发出错误消息.但是,我在创建带有.cpp文件的头文件时无法保存该方法.
头文件:
//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
void arrayLengthCheck(int & length, const int capacity, string prompt);
#endif // ARRAYHELPER_H
Run Code Online (Sandbox Code Playgroud)
代码文件:
//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;
}
}
Run Code Online (Sandbox Code Playgroud)
运行此main.cpp文件,其中包含头文件中的#include "arrayHelper.h"错误string is not declared.在头文件中包含字符串无效,但会#include "arrayHelper.cpp"导致重新定义方法.我该如何处理这个问题?
你应该#include <string>在标题中,并引用stringas std::string,因为using namespace std在头文件中是一个坏主意.其实,这是一个在坏主意.cpp太.
//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
#include <string>
void arrayLengthCheck(int & length, const int capacity, std::string prompt);
#endif // ARRAYHELPER_H
Run Code Online (Sandbox Code Playgroud)