首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C3848上修复vs2013错误?

如何在C3848上修复vs2013错误?
EN

Stack Overflow用户
提问于 2015-03-15 07:23:33
回答 1查看 5K关注 0票数 6

我试图使用C++在VS2013上实现最佳优先搜索。下面是密码。

代码语言:javascript
复制
    //node for tree
    struct Node
    {
        Node(std::string const& s, std::string const& p)
            : state(s), path(p)
        {}

        const std::string state;
        const std::string path;
    };

    //heuristic functor
    struct ManhattanDistance
    {
        std::size_t operator()(std::string const& state, std::string const& goal)
        {
            std::size_t ret = 0;
            for (int index = 0; index != goal.size(); ++index)
            {
                if ('0' == state[index])
                    continue;

                auto digit = state[index] - '0';
                ret += abs(index / 3 - digit / 3) + abs(index % 3 - digit % 3);// distance(row) plus distance(col)
            }

            return ret;
        }
    };

    //functor to compare nodes using the heuristic function.
    template<typename HeuristicFunc>
    struct GreaterThan
    {
        explicit GreaterThan(HeuristicFunc h, std::string const& g = "012345678")
            : goal(g), heuristic(h)
        {}

        bool operator()(Node const& lhs, Node const& rhs) const
        {
            return heuristic(lhs.state, goal) > heuristic(rhs.state, goal);
            return true;
        }

        const std::string goal;
        const HeuristicFunc heuristic;
    };

在单元测试中测试此代码时,编译器抱怨:

错误1错误C3848:具有类型'const::search::曼哈顿距离‘的表达式将丢失一些const -易失性限定符,以便调用'size_t曼哈顿距离::运算符()(const std::string &,const std::string &)’

如何理解这个错误?怎么修呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-15 07:27:40

您的方法std::size_t ManhattanDistance::operator()(std::string const& state, std::string const& goal)没有被声明为const,但是您尝试在const ManhattanDistance对象上调用它。编译器正确地拒绝了这个格式错误的程序。

更改定义行以声明方法const

代码语言:javascript
复制
std::size_t operator()(std::string const& state, std::string const& goal) const
//                                                                        ^^^^^
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29058254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档