读书人

程序出点了小异常求大侠解释

发布时间: 2012-03-25 20:55:16 作者: rapoo

程序出点了小错误,求大侠解释
# include<iostream.h>
# include<string>
using namespace std;

template<int hi,int wid>
class Screen
{
friend ostream& operator<<(ostream &os,const Screen<hi,wid> &s);
friend istream& operator>>(istream &is,Screen<hi,wid> &s);
public:
Screen():Screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}
private:
string screen;
string::size_type cursor;
string::size_type height,width;
};

ostream& operator<<(ostream &os,const Screen<hi,wid> &s)
{
os<<s[cursor];
return os;
}
istream& operator>>(istream &is,Screen<hi,wid> &s)
{
is>>s.height>>s.width>>s.cursor;
s.screen(height*width,'#');
return is;
}


编译出现了好多错误,大侠看看!
输出输入不用模板!

[解决办法]

C/C++ code
#include <iostream>#include <string>using namespace std;template<int hi,int wid>class Screen{    friend ostream& operator<<(ostream &os,const Screen<hi,wid> &s);    friend istream& operator>>(istream &is,Screen<hi,wid> &s);public:    Screen():Screen(hi*wid,'#'),cursor(0),height(hi),width(wid){}private:    string screen;    string::size_type cursor;    string::size_type height,width;};template<int hi,int wid> ostream& operator<<(ostream &os,const Screen<hi,wid> &s){    os<<s[cursor];    return os;}template<int hi,int wid> istream& operator>>(istream &is,Screen<hi,wid> &s){    is>>s.height>>s.width>>s.cursor;    s.screen(height*width,'#');    return is;}
[解决办法]
friend ostream& operator<<(ostream &os,const Screen<hi,wid> &s);
因为你重载输出操作符的函数参数列表中有Screen<hi,wid> &s,而hi,wid,是该类的模板形参,所以定义输出操作符重载函数时,必须有template<int hi,int wid>这个模板,如果没有这个模板的话,你的函数形参中的hi,wid在编译的时候是无法识别的标识符,如果函数形参列表中没有hi,wid,也就不用函数模板了

读书人网 >C++

热点推荐