考虑thisquestion,也就是下面的代码没有编译:std::vectora,b;std::cout它无法编译,因为vectorcomparisonoperators对于vector是非成员函数模板,不允许考虑隐式转换。但是,如果将运算符改为非成员非模板,friend功能:template>classvector{//...friendbooloperator那么这个版本的operator会被ADL发现并被选为最佳可行的重载,并且原始示例将被编译。鉴于此,是否有理由更喜欢我们目前拥有的非成员函数模板,或者这是否应该被视为标准中的缺陷? 最佳答案
每个标准容器都有一个begin和end方法用于返回该容器的迭代器。然而,C++11显然引入了名为std::begin的免费函数。和std::end它调用begin和end成员函数。所以,不要写autoi=v.begin();autoe=v.end();你会写autoi=std::begin(v);autoe=std::end(v);在他的演讲中,WritingModernC++,HerbSutter说,当您需要容器的开始或结束迭代器时,现在应该始终使用自由函数。但是,他没有详细说明您想要为什么。查看代码,它为您节省了一个字符。因此,就标准容器而言,免费功能似乎完全没用。HerbSutt
赋值运算符可以使用成员函数重载,但不能使用非成员friend函数:classTest{inta;public:Test(intx):a(x){}friendTest&operator=(Test&obj1,Test&obj2);};Test&operator=(Test&obj1,Test&obj2)//Notimplementedfully.justfortest.{returnobj1;}它会导致这个错误:errorC2801:'operator='mustbeanon-staticmember为什么不能使用friend函数来重载赋值运算符?编译器允许使用friend重载其他运算符
赋值运算符可以使用成员函数重载,但不能使用非成员friend函数:classTest{inta;public:Test(intx):a(x){}friendTest&operator=(Test&obj1,Test&obj2);};Test&operator=(Test&obj1,Test&obj2)//Notimplementedfully.justfortest.{returnobj1;}它会导致这个错误:errorC2801:'operator='mustbeanon-staticmember为什么不能使用friend函数来重载赋值运算符?编译器允许使用friend重载其他运算符