C++ headers redefining/declaring mixup

邮差的信 提交于 2019-12-02 11:52:38
juanchopanza

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

string is used in header file but can't find the symbol.

Move #include <string> to arrayHelper.h and replace all string with std::string

Side note:

call using namespace std; locally is idiomatic way, and pass prompt by reference can elide one copy. Below is slightly enhancement to your code:

arrayHelper.h

#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H

#include <string>

void arrayLengthCheck(int & length, const int capacity, const std::string& prompt);

#endif // ARRAYHELPER_H

arrayHelper.cpp

#include <iostream>
#include "arrayHelper.h"

void arrayLengthCheck(int & length, const int capacity, const std::string& prompt)
{
   using namespace std;    

    // 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;
    }
}

You need to say std::string in your header file...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!