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

C++ headers redefining/declaring mixup(C++ 头文件重新定义/声明混淆)

本文介绍了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++ 头文件重新定义/声明混淆

基础教程推荐