关于非类型形参的模板中重载输出操作符
#include<iostream>
#include<string>
using namespace std;
//可能是小白的问题,先谢谢大家咯
template <int hi, int wid>
class Screen
{
friend ostream& operator<<(ostream &out, const Screen<hi, wid> &sr);//怎么这样重载会有错误?
private:
string scr_name;
string::size_type cursor;
string::size_type height, width;
public:
Screen():scr_name(hi*wid, '#'), cursor(0), height(hi), width(wid){}
};
template<int hi, int wid> ostream& operator<< (ostream &out, const Screen<hi, wid> &sr)
{
out << sr.scr_name << sr.cursor << sr.height << sr.width << endl; //不是已经是模板的友元 了吗,怎么编译时说不能访问私有成员?
return out;
}
int main()
{
Screen<5, 2> sr;
cout << sr;
return 0;
}
error C2248: 'scr_name' : cannot access private member declared in class 'Screen<5,2>'
D:\MSDev98\c++primer\tstt\0.cpp(10) : see declaration of 'scr_name'
D:\MSDev98\c++primer\tstt\0.cpp(25) : 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<5,2> &)' being compiled
D:\MSDev98\c++primer\tstt\0.cpp(19) : error C2248: 'cursor' : cannot access private member declared in class 'Screen<5,2>'
D:\MSDev98\c++primer\tstt\0.cpp(11) : see declaration of 'cursor'
D:\MSDev98\c++primer\tstt\0.cpp(25) : 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<5,2> &)' being compiled
D:\MSDev98\c++primer\tstt\0.cpp(19) : error C2248: 'height' : cannot access private member declared in class 'Screen<5,2>'
D:\MSDev98\c++primer\tstt\0.cpp(12) : see declaration of 'height'
D:\MSDev98\c++primer\tstt\0.cpp(25) : 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<5,2> &)' being compiled
D:\MSDev98\c++primer\tstt\0.cpp(19) : error C2248: 'width' : cannot access private member declared in class 'Screen<5,2>'
D:\MSDev98\c++primer\tstt\0.cpp(12) : see declaration of 'width'
D:\MSDev98\c++primer\tstt\0.cpp(25) : 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<5,2> &)' being compiled
执行 cl.exe 时出错.
0.obj - 1 error(s), 0 warning(s)
[解决办法]
friend ostream& operator<< <hi, wid>(ostream &out, const Screen<hi, wid> &sr);
[解决办法]
楼主,珍惜生命,远离VC6