求各位大大帮忙,怎么在类模板【非类型形参】中将重载的<<操作符设为友元
代码如下
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下进行但是报错了,求各位大大帮忙,
[解决办法]
#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;}