在我遇到这个错误之前,我真的以为我理解了 C++ 中的指针/引用。
问题:
将数据分配给引用的返回值不会更改数据结构中的数据。
我试过的:
我确信这是一个概念性问题,但是在重新阅读有关指针和引用的教程后,我似乎仍然无法确定问题所在。
编码:
在标题中
template <class directed_graph_type>
typename directed_graph<directed_graph_type>::vertex& directed_graph<directed_graph_type>::add_vertex(directed_graph_type& obj)
{
    // create new vertex
    vertex* v = new vertex;
    v->vertex_data = obj;
    // adding to list
    vertices.push_back(v);
    return *v;
}
注意:从函数中可以看出,返回了一个引用。这使我相信在以下代码中更改顶点数据的值也会更改列表结构中的值。但是,在迭代时,我发现情况并非如此。
在主要
// assigning
directed_graph<int> graph;
int a = 1;
directed_graph<int>::vertex v1 = graph.add_vertex(a);
v1.data() = 20;
cout << v1.vertex_data << endl; // output: 20
// iterating through
std::list<directed_graph<int>::vertex*>::iterator it = graph.vertices.begin();
while(it != graph.vertices.end())
{
    cout << (*it)->vertex_data << endl; // output: 1
    ++it;
}
类声明(以防万一)
template <class directed_graph_type>
class directed_graph
{
public:
    class vertex;
    virtual ~directed_graph();
    vertex& add_vertex(directed_graph_type& obj);
    void add_connection(vertex& from, vertex& to);
    void remove_vertex(vertex& v);
    void remove_connection(vertex& from, vertex& to);
    iterator begin();
    iterator end();
    std::list<vertex*> vertices;
    class vertex
    {
    public:
        void add_connection(vertex& to);
        void remove_connection(vertex& to);
        iterator begin();
        iterator end();
        directed_graph_type& data();
        directed_graph_type vertex_data;
        std::list<vertex*> connected_to;
    };
};