c++ - 错误 : passing 'const string' as this argument of push_back

标签 c++ string

我在第 19 行的以下代码中遇到名义错误

#include <string>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;

namespace robot_name 
{
    vector<string> allRobotNames;
    class robot
    {
        public:
            string robotName;

            string name() const
            {
                if(robotName.empty())
                {
                    robotName.push_back('a'+rand()%26);//this line
                    robotName.push_back('a'+rand()%26);//also here
                    robotName+=to_string(rand()%10) + to_string(rand()%10) + to_string(rand()%10);//and here
                    return robotName;
                }
                else
                {
                    return robotName;
                }
            };

            void reset() const
            {
                allRobotNames.push_back(robotName);
                while(find(allRobotNames.begin(), allRobotNames.end(), robotName)!=allRobotNames.end())
                {
                    robotName="";//here as well
                    robotName.push_back('a'+rand()%26);
                    robotName.push_back('a'+rand()%26);
                    robotName+=to_string(rand()%10) + to_string(rand()%10) + to_string(rand()%10);
                };
            };
    };
};

另外,第20、21、35行也有类似的错误。该类实例化为const robot_name::robot robot,然后调用robot.name()如图所示。我已经完成了以相同方式实例化类的其他代码,但是我没有收到此错误。有人可以检查一下是否存在可能的错误并告诉我一些可能的解决方案吗?提前谢谢你。

最佳答案

namereset 函数是const。这意味着您不能更改这些函数中的任何成员。例如,您在 allRobotNames.push_back 函数中这样做。

要么使 resetname 非常量函数,或者将 robotName 声明为 mutable:

mutable string robotName;

但是不要滥用 mutable。仅当使用 mutable 有意义时才应该使用它(例如,对象中没有会影响对象用户的更改)。

如果您使用 mutable 只是为了能够更改类成员的值,这还不足以成为使用它的理由。

关于c++ - 错误 : passing 'const string' as this argument of push_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26822598/

相关文章:

c++ - imshow 不工作

c++ - 不包括 Qt QMimeDatabase header

java - 如何创建还没有值的字符串数组

string - 从字符序列制作字符串

c++ - 声明模板时指向成员函数语法的指针

c++ - 不允许继承成员,为什么?

ios - 了解 Swift 中的 UnicodeScalar 初始值设定项

string - 如何在类似列表的模式匹配中使用 scala 字符串

c++ - 如何在二维 vector 上进行内存设置

python - Python 中的类型提示特定字符​​串列表