+ -
当前位置:首页 → 问答吧 → 怎么将一个函数放到头文件中?

怎么将一个函数放到头文件中?

时间:2011-12-22

来源:互联网

是这样的,我写了一个函数get,再get.h文件中申明了,然后再get.cpp中实现,再main.cpp中使用,但是出现了错误
求解
get.h
C/C++ code
#ifndef GET_H_INCLUDED
#define GET_H_INCLUDED
extern istream &get(istream& gt)



#endif // GET_H_INCLUDED


get.cpp
C/C++ code
#include <iostream>
#include <stdexcept>
#inlucde "get.h"
using namespace std;
istream &get(istream& gt)
{
    string a;
    while(gt>>a)
    {
        if(gt.bad())
        throw runtime_error("iostream is corrupted");
        cout<<a<<endl;
    }
    return gt;
}


main.cpp
C/C++ code
#include <iostream>
#include "get.h"
using namespace std;
int main()
{
    double ival;
    get(cin);
    cin>>ival;
    cout<<ival;
    return 0;
}



编译出错信息如下:
C:\Users\admin\Documents\Codeblocks\text\get.h|3|error: expected initializer before '&' token|
C:\Users\admin\Documents\Codeblocks\text\main.cpp||In function 'int main()':|
C:\Users\admin\Documents\Codeblocks\text\main.cpp|7|error: 'cin' was not declared in this scope|
C:\Users\admin\Documents\Codeblocks\text\main.cpp|7|error: 'get' was not declared in this scope|
C:\Users\admin\Documents\Codeblocks\text\main.cpp|9|error: 'cout' was not declared in this scope|
||=== Build finished: 4 errors, 0 warnings ===|

作者: itelly   发布时间: 2011-12-22

是命名空间和函数声明有问题?帮你修改如下
C/C++ code

// get.h
#ifndef GET_H_INCLUDED
#define GET_H_INCLUDED

#include<iostream>
using std::istream;
istream &get(istream& gt);

#endif // GET_H_INCLUDED



改完你再试试,另外,不知道你的函数的意图是什么

作者: seucs   发布时间: 2011-12-22