使用stl函数对象的一些错误

 

不知道为什么字体颜色变不过来,本来强调的部分是用红色标出的,现在只能是灰色的部分,将就着看吧。

先看一段代码:

 

#include ... // 包含必要的头文件

 

 

template <class T1, class T2, class T3>

 

 

 

struct ToFile : binary_function<T1, T2, T3>

{

T3 operator()(T1 p, T2 of)

{

of<<p.first<<": "<<p.second<<endl;

 

}

};

 

int main()

{

map<int, int> m; m[1] = 0; m[2] = 0; m[7] = 0;


ofstream of; of.open("times.txt"); for_each(m.begin(), m.end(), bind2nd(ToFile<pair<int,int>,ofstream,void>(), of)); of.close();

}

这段代码是要把map容器中的内容写入文件中。
编译提示:error C2248: “std::basic_ios<_Elem,_Traits>::basic_ios”: 无法访问 private 成员(在“std::basic_ios<_Elem,_Traits>”类中声明
查了一下basic_ios的定义,他的拷贝构造函数和赋值操作符都是私有的,说明不能进行拷贝,而stl使用的方式是copy-in-copy-out,那么就无法使用上述代码的方式来进行保存了,那么不能拷贝对象,拷贝引用怎么样?于是将for_each中的那部分改成如下代码:

 

template <class T1, class T2, class T3>

struct ToFile : binary_function<T1, T2, T3>

{

T3 operator()(T1 p, T2 of)

{

of<<p.first<<": "<<p.second<<endl;

}

};

 

int main()

{

map<int, int> m;

 

m[1] = 0;

m[2] = 0;

m[7] = 0;

 

ofstream of; of.open("times.txt");

for_each(m.begin(), m.end(), bind2nd(ToFile<pair<int,int>,ofstream &,void>(), of)); of.close();

}

 

继续编译,结果是error C2529: “_Right”: 引用的引用非法

想想是怎么回事,ToFile中的类型是ofstream&,由于bind2nd的模板参数定义是ToFile::second_argument_type&,也就是ToFile::ofstream &&,就是引用的引用,c++中是不允许的,所以编译出错。那怎么办呢?

引用不行,那就用指针来解决吧,代码就变成这个样子:

 

 

template <class T1, class T2, class T3>

struct ToFile : binary_function<T1, T2, T3>

{

T3 operator()(T1 p, T2 of)

{

(*of)<<p.first<<": "<<p.second<<endl;

}

};

 

int main()

{

map<int, int> m;

 

 

m[1] = 0;

m[2] = 0;

m[7] = 0;

 

ofstream of;

of.open("times.txt");

for_each(m.begin(), m.end(), bind2nd(ToFile<pair<int,int>,ofstream*,void>(), &of));

of.close();

}

这下总行了吧,编译有提示错误:error C3848: 具有类型“const ToFile<T1,T2,T3>”的表达式会丢失一些 const-volatile 限定符以调用“void ToFile<T1,T2,T3>::operator ()(T1,T2),晕倒,怎么回事?

原来const类型的变量,只能调用const类型的函数,所以给operator()加上一个const就行了,如下:

 

 

template <class T1, class T2, class T3>

struct ToFile : binary_function<T1, T2, T3>

{

T3 operator()(T1 p, T2 of) const

{

(*of)<<p.first<<": "<<p.second<<endl;

}

};

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值