首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求各位大大帮忙,如何在类模板【非类型形参】中将重载的<<操作符设为友元

2012-04-23 
求各位大大帮忙,怎么在类模板【非类型形参】中将重载的操作符设为友元代码如下templateint hi,int widcl

求各位大大帮忙,怎么在类模板【非类型形参】中将重载的<<操作符设为友元
代码如下


template<int hi,int wid>
class Screen
{
friend std::ostream& operator << <hi,wid>(std::ostream& , const Screen<hi, wid>&);
friend std::istream& operator << <hi,wid>(std::istream& , const Screen<hi, wid>&);
public:
....
private:
  std::string contents;
index cursor;
index height,width;
}
//////////////////////////////////////////////////////////////


template<int hi,int wid>
std::ostream& operator<<(std::ostream& os,const Screen<hi,wid> &s)
{
os<<"height:"<<s.height
<<"width:"<<s.width
<<"contents:"<<s.contents;
return os;
}
template<int hi,int wid>
std::istream& operator>>(std::istream &is,Screen<hi,wid>& s)
{
std::string cont;
is>>s.height>>s.width>>cont;
s.contents.assign(s.height*s.width,' ');
if(cont.size()!=0)
return is;
}
怎么才能让两个重载的操作符能成为Screen的对象,并且能够被调用???有时候不调用的时候连接没错,但是调用后连接就错了,这个事c++primer的习题16.39,在VC++2008下进行但是报错了,求各位大大帮忙,

[解决办法]

C/C++ code
#include<string>#include<iostream>using namespace std;typedef  int index;template<int hi, int wid>class Screen{    friend std::ostream& operator << <> ( std::ostream& , const Screen<hi, wid>& );    friend std::istream& operator << <> ( std::istream& , const Screen<hi, wid>& );public:private:    std::string contents;    index cursor;    index height, width;};template<int hi, int wid>std::ostream& operator<< <>( std::ostream& os, const Screen<hi, wid> &s ){    os << "height:" << s.height       << "width:" << s.width       << "contents:" << s.contents;    return os;}template<int hi, int wid>std::istream& operator>> <> ( std::istream &is, Screen<hi, wid>& s ){    std::string cont;    is >> s.height >> s.width >> cont;    s.contents.assign( s.height * s.width, ' ' );    if( cont.size() != 0 )        return is;}int main(){    Screen<10, 20> x;    cout << x;    return 0;} 

热点排行