C++ headers redefining/declaring mixup(C++ 头文件重新定义/声明混淆)
问题描述
我试图从一个简单的程序中抽象出一个方法.此方法根据预先声明的 CAPACITY 常量测试数组的长度,如果不满足条件,则会发出错误消息.但是,我无法使用 .cpp 文件创建头文件来保存该方法.
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, '
');
// ...display helpful error message and accept a new set of inputs
cout << "List length must be less than " << capacity << ".
" << prompt;
cin >> length;
}
}
运行这个包含 #include "arrayHelper.h" 的 main.cpp 文件会出错,因为在头文件中没有声明 string.在头文件中包含字符串无效,但 #include "arrayHelper.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>在header中,把string称为std::string,因为 using namespace std 在头文件中是个坏主意.实际上,这是 .cpp 也是.
You should #include <string> in the header, and refer to string as std::string, since using namespace std would be a bad idea in a header file. In fact it is a 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++ 头文件重新定义/声明混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 头文件重新定义/声明混淆
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
