传递const丢弃限定符

时间:2018-04-28 07:50:02

标签: c++ set const

我试图实现无向图:

template<typename NodeType, typename Edge>
class Graph {
public:
    Graph() = default;

    Graph& Add(const Edge &edge, const NodeType &from, const NodeType &to) {
        auto node = graph.emplace(Node(from)); //passing ‘const std::set<Graph<City, Train>::Node, std::less<Graph<City, Train>::Node>, std::allocator<Graph<City, Train>::Node> >’ as ‘this’ argument discards qualifiers
        (node.first)->edges.emplace_back(edge);

        node = graph.emplace(Node(to));
        (node.first)->edges.emplace_back(edge);

        return *this;
    }

    void PrintGraph() const {
        for(const auto &node : graph) {
            cout << node.id << ":" << endl;
            for(const auto &edge : node.edges)
                cout << "-> " << edge << endl;
        }
    }
private:
    class Node {
    public:
        Node(const NodeType &val): id(val) {}
        Node(const Node &other): id(other.id) {
            copy(other.edges.begin(), other.edges.end(), edges);
        }

        bool operator<(const Node &other) const {
            return id < other.id;
        }

        NodeType id;
        vector<Edge> edges;
    };

    set<Node> graph;
};

由于我的(node.first)->edges.emplace_back()error: passing ‘const std::vector<Train, std::allocator<Train> >’ as ‘this’ argument discards qualifiers [-fpermissive]我不理解,因此无法编译:

  • 成员函数Add()返回对自身的引用,因为我想链接它。它不能是const reference,因为函数会修改其类成员。

  • 成员函数Add()不能是const,因为它可以添加节点或节点的优势。

  • graph.emplace()可能会返回pair<set::const_iterator,bool>,所以我尝试通过更改为pair<set<Node>::const_iterator,bool> node =来验证它,但随后会出现一系列新问题:类型/值参数1不匹配。我认为set::emplace将一对迭代器返回到new / existing元素,并返回true / false,具体取决于是否添加了新元素。我在哪里错了?

那么我的Add()出了什么问题?

我在以下类中使用模板化图形类:

class City {
public:
    City(const string &cityName): name(cityName) {}
    City(const City &cpy) = default;

    friend ostream& operator<<(ostream &os, const City &city) {
        os << city.name;
        return os;
    }
    bool operator<(const City &other) const {
        return this->name < other.name;
    }
    bool operator==(const City &other) const {
        return this->name == other.name;
    }

    string name;
};

class Train {
public:
    Train(const string &trainName): name(trainName) {}
    Train(const Train &cpy) = default;

    friend ostream& operator<<(ostream &os, const Train &train) {
        os << train.name;
        return os;
    }
    bool operator<(const Train &other) {
        return this->name < other.name;
    }
    bool operator==(const Train &other) const {
        return this->name == other.name;
    }

    string name;
};

这个类是这样使用的:

Graph<City,Train> network;

network.Add(Train("train 1"), City("city 1"), City("city 2")).Add(Train("train 2"), City("city 1"), City("city 2"));

0 个答案:

没有答案