我有一个const正确性问题,我似乎无法解决。下面是我的程序结构:如何让这个常量纠正?
class Node
{
private:
int id;
std::set<Node*> neighbours;
public:
Node();
Node(int id_p);
void set_id(const int& id_p);
int get_id() const;
void add_neighbour(Node* neighbour);
bool is_neighbour(Node* neighbour) const;
friend bool operator <(const Node& lhs, const Node& rhs);
};
class Graph
{
private:
std::set<Node> node_list;
public:
Graph();
void add_node(int id);
const Node* get_node_by_id(int id) const;
bool has_node(int id) const;
void check_add_node(int id);
void add_edge(int id_1, int id_2);
bool has_edge(int id_1, int id_2) const;
void check_add_edge(int id_1, int id_2);
(...)
};
现在的问题是,如果我调用函数Graph::get_node_by_id()
,我想返回一个指向给定节点(类型Node
)。但这似乎是不可能的,因为std::set
隐式地将我的节点类型对象转换为const Node
对象,而我无法从const
对象获取non-const pointer
对象。
但是,我不能拥有一切设置为const Node
(这将解决这个问题),因为我想打电话给Node::add_neighbour()
从Graph::add_edge()
,但每当我这样做,我的编译器说,我可能会违反const
岬(必填以获得排序集)node_list
集中的元素,尽管我将less operator<
定义为仅关注id
。
有什么我可以做的,以解决这个困境(没有放弃有排序集)?谢谢您的反馈!在错误
更多信息:
如果我使用非恒定的领域,错误Graph::get_node_by_id()
:
for(Node& element : this->node_list) // Error: element should be const Node&
{
if(element->get_id() == id)
{
return element;
}
}
return nullptr;
如果我使用常量领域,错误Graph::add_edge()
:
(...)
const Node* node_1 = this->get_node_by_id(id_1);
const Node* node_2 = this->get_node_by_id(id_2);
node_1->add_neighbour(node_2); // Error for disregarding constness
node_2->add_neighbour(node_1);
听起来像你可能想有一个'映射'映射ID节点,而不是一组。 –
user2357112
也许我错过了什么,但为什么不把内部设置为可变? –