#include <iostream>using namespace std;class alloc { };template <typename T,typename Alloc = alloc>class vector{public: voID swap(vector<T,Alloc> &v) { cout << "swap()" << endl; }};template <typename T,typename Alloc>voID swap(const vector<T,Alloc> &v1,const vector<T,Alloc> &v2){ v1.swap(v2);}int main(){ vector<int> x; vector<int> y; swap(x,y); return 0;}
代码片段运行没有问题.但我无法获得任何输出
然后我删除const关键字.
voID swap(vector<T,vector<T,Alloc> &v2)
我得到输出交换()
我读过“原因是参数的const只在函数中本地应用,因为它正在处理数据的副本.这意味着函数签名实际上是相同的.”
所以我认为写或不写const没有区别.如果我坚持在这里写const,我如何修改代码以获得输出swap()
解决方法 这是为什么应该避免使用std的一个很好的例子.为了调试此问题,请使用std删除,并在需要标准库行为的位置添加std ::.幸运的是,只有一个这样的地方,即模板类中的交换函数:
voID swap(vector<T,Alloc> &v) { std::cout << "swap()" << std::endl; }
现在尝试再次编译到see the error,以防止使用const交换:
prog.cpp:19:5: error: passing
const vector<int>
asthis
argument discards qualifIErs
当你的程序使用时,当你的函数不适用时,你可以选择使用自己的交换函数选择std::swap
.这正是它所做的,没有任何警告,因为它假设它是你想要它做的.
该错误还告诉您如何使const限定向量被接受:将const添加到vector :: swap的参数中,如下所示:
voID swap(const vector<T,Alloc> &v) const { std::cout << "swap()" << std::endl; }
现在你的程序编译并再次运行(demo).
总结以上是内存溢出为你收集整理的c – 带有函数签名的Const关键字全部内容,希望文章能够帮你解决c – 带有函数签名的Const关键字所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)