2016-04-23 49 views
3

const关键字这里是我的简单的代码:与函数签名

#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,Alloc> &v1,vector<T,Alloc> &v2) 

我得到的输出swap()

我已阅读“的原因是,常量的参数只能在函数中局部适用,因为它正在对数据的拷贝。这意味着函数签名反正真的是一样的。“

所以我想有写之间没有差异或不写const.if我坚持在这里写常量,我如何修改代码来获取输出swap()

+4

试着改变你的类名'vector'和函数名'swap'到别的东西,它们与STL的名字冲突。 – songyuanyao

回答

7

这就是为什么using std应该一个很好的例证应避免。

为了调试此问题,请删除using std,并将std::添加到您想要标准库中的行为的地方。幸运的是,只有一个这样的地方,即在模板类的swap功能:

void swap(vector<T,Alloc> &v) { std::cout << "swap()" << std::endl; } 

现在尝试被再次使用编译成see the error防止您的swapconst

prog.cpp:19:5: error: passing const vector<int> as this argument discards qualifiers

当你的程序是using std当你的函数不适用时,C++有一个选择std::swap而不是你自己的swap函数。这正是它所做的,没有任何警告,因为它假定它是你想要它做的。

错误还告诉你什么,以使const -qualified向量做被接受:添加constvector::swap的参数,如:

void swap(const vector<T,Alloc> &v) const { std::cout << "swap()" << std::endl; } 

现在你的程序编译并再次运行(demo )。