读书人

如何将一个函数放到头文件中

发布时间: 2012-02-23 22:01:36 作者: rapoo

怎么将一个函数放到头文件中?
是这样的,我写了一个函数get,再get.h文件中申明了,然后再get.cpp中实现,再main.cpp中使用,但是出现了错误
求解
get.h

C/C++ code
#ifndef GET_H_INCLUDED#define GET_H_INCLUDEDextern 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 ===|


[解决办法]
是命名空间和函数声明有问题?帮你修改如下
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
[解决办法]
extern istream &get(istream& gt);

[解决办法]
你那个include写错啦

读书人网 >C++

热点推荐