为什么const阻止它编译?

问题描述 投票:1回答:1

我不确定如何在不创建额外变量的情况下解决此问题。这是无法编译的代码:

std::string & printVec(std::vector<double> const &ds, std::string &dum) {
    std::vector<double>::iterator it;
//    std::vector<double> dsi = ds; // Created just to get the code to work, using dsi.begin() etc. 
    dum = " ";
    for (it = ds.begin(); it != ds.end(); it++) { // Compiler error. No suitable "="
        dum = dum + std::to_string(*it) + " ";
    }
    return dum;
}

如果删除输入上的const,它将编译:

std::string & printVec(std::vector<double> &ds, std::string &dum) {
    std::vector<double>::iterator it;
    dum = " ";
    for (it = ds.begin(); it != ds.end(); it++) {
        dum = dum + std::to_string(*it) + " ";
    }
    return dum;
}

我有理由想要const。什么是获得相同功能但不删除const的方法?

c++ const
1个回答
2
投票

A const_iterator是一个指向const值的迭代器(类似于const T *指针);取消引用它会返回对常量值(const T&)的引用,并防止修改引用的值:它强制执行const-correctness

具有对容器的const引用时,只能获得const_iterator。

将迭代器更改为const_iterator:

std::vector<double>::const_iterator it;

或使用auto

for (auto it = ds.begin(); it != ds.end(); it++) { // Compiler error. No suitable "="
    dum = dum + std::to_string(*it) + " ";
}

range based for loop

for (auto a: ds)
    dum = dum + std::to_string(a) + " ";
© www.soinside.com 2019 - 2024. All rights reserved.