加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 带有函数签名的Const关键字

发布时间:2020-12-16 10:02:30 所属栏目:百科 来源:网络整理
导读:这是我的简单代码: #include iostreamusing namespace std;class alloc { };template typename T,typename Alloc = allocclass vector{public: void swap(vectorT,Alloc v) { cout "swap()" endl; }};template typename T,typename Allocvoid swap(const ve
这是我的简单代码:

#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> as this argument discards qualifiers

当你的程序使用时,当你的函数不适用时,你可以选择使用自己的交换函数选择std::swap.这正是它所做的,没有任何警告,因为它假设它是你想要它做的.

该错误还告诉您如何使const限定向量被接受:将const添加到vector :: swap的参数中,如下所示:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读