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++ 头文件重新定义/声明混淆
基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01