|
源程序:
template<int hi,int wid>
class Screen
{
public:
Screen():_cursor(0),_Screen(hi*wid,'#'){}
void home(){_cursor=0;}
void move(int,int);
char get(){return _Screen[_cursor];}
char get(int,int);
bool checkRange(int,int);
void copy(const Screen&);
void set(char c){_Screen=string(hi*wid,c);}
void set(const string&);
void set(const Screen&);
friend ostream& operator<<(ostream &out,const Screen<hi,wid> &s);
friend istream& operator>>(istream &in,Screen<hi,wid> &s);
private:
string _Screen;
int _cursor;
};
template<int hi,int wid>
ostream& operator<<(ostream &out,const Screen<hi,wid> &s)
{
for(int i=1;i<=hi;++i)
{
for(int j=1;j<=wid;++j)
out<<s.get(i,j); //C2663: 'get' : 2 overloads have no legal conversion for 'this' pointer
cout<<endl;
}
cout<<endl;
return out;
}
template<int hi,int wid>
istream& operator>>(istream &in,Screen<hi,wid> &s)
{
s.home();
for(int i=1;i<=hi;++i)
for(int j=1;j<=wid;++j)
in>>s._Screen[s._cursor++]; //友元为什么不能访问私有成员
return in;
}
template<int hi,int wid>
void Screen<hi,wid>::move(int row,int col)
{
if(checkRange(row,col))
{
int r=(row-1)*wid;
_cursor=col-1+r;
}
}
template<int hi,int wid>
bool Screen<hi,wid>::checkRange(int row,int col)
{
if(row<1||row>hi||col<1||col>wid)
{
cerr<<"System coordinate("
<<row<<","<<col
<<") out of bounds.\n";
return false;
}
return true;
}
template<int hi,int wid>
char Screen<hi,wid>::get(int r,int c)
{
move(r,c);
return get();
}
template<int hi,int wid>
void Screen<hi,wid>::copy(const Screen &sobj)
{
if(this!=&sobj)
{
_cursor=sobj._cursor;
_Screen=sobj._Screen;
}
}
template<int hi,int wid>
void Screen<hi,wid>::set(const Screen &s)
{
for(int r=1;r<=hi;++r)
for(int c=1;c<wid;++c)
{
move(r,c);
_Screen[_cursor]=s[_cursor];
}
}
template<int hi,int wid>
void Screen<hi,wid>::set(const string &s)
{
for(int r=1;r<=hi;++r)
for(int c=1;c<=wid;++c)
{
move(r,c);
_Screen[_cursor]=s[_cursor];
}
}
int main(void)
{
Screen<2,3> s1;
cout<<s1;
cout<<"please enter 6(chars):";
cin>>s1;
cout<<s1;
return 0;
}
功能描述:
我定义了一个类模板Screen<hi,wid>,想通过类模板中的friend input&output操作符输出Screen<2,3> s1中的内容
但是,友元的定义有问题:
问题1:error C2663: 'get' : 2 overloads have no legal conversion for 'this' pointer
d:\programe\c++ primer\test3\main.cpp(26) : see reference to function template instantiation 'class std::basic_ostream<char,struct std::char_traits<char> > &__cdecl operator <<(class std::basic_ostream<char,struct std::char_traits<char> > &,
const class Screen<2,3> &)' being compiled
问题2: error C2248: '_Screen' : cannot access private member declared in class 'Screen<2,3>'
d:\programe\c++ primer\test3\screen.h(29) : see declaration of '_Screen'
谢谢:) |
|