c++ - 特定的 c++ 指针/引用错误?

标签 c++ pointers data-structures reference runtime-error

在遇到这个错误之前,我真的以为我理解了 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;
    };
};

最佳答案

directed_graph<int>::vertex v1 = graph.add_vertex(a);

这里 v1 不是引用变量。返回的引用将被复制v1中(而不是仅仅让v1引用同一个变量)从而改变v1 不会改变原来的。

试试这个:

directed_graph<int>::vertex &v1 = graph.add_vertex(a);

关于c++ - 特定的 c++ 指针/引用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19895870/

相关文章:

c++ - 如果语句位于cout行中,是否有办法?

c - * 对于结构是非法的吗?

c++ - 二叉树析构函数的递归调用

java - 检查给定字符串是否与其他两个字符串交错

c++ - 将 short int[] 转换为 char*

c++ - 转义字符包含在字符串中

使用 gcc 的 c++ makefile - 从子文件夹列表生成源文件列表

c - 如何将我的指针初始化为 NULL

c++ - 指向虚拟成员函数的指针

c++ - 类返回类型重载