【问题标题】:How to fix this C3848 error on vs2013?如何在 vs2013 上修复此 C3848 错误?
【发布时间】:2015-05-17 11:18:23
【问题描述】:

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

    //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 ai::search::ManhattanDistance' 的表达式将丢失一些 const-volatile 限定符,以便调用 'size_t ManhattanDistance::operator ()(const std::string &,const std ::字符串 &)'

如何理解这个错误?如何解决?

【问题讨论】:

标签: c++ visual-studio templates c++11


【解决方案1】:

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

更改定义行以声明方法const

std::size_t operator()(std::string const& state, std::string const& goal) const
//                                                                        ^^^^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2014-03-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多