c++ - 使用指针的条件

标签 c++

我已经阅读了关于“指针”的主题,但我仍然有一些疑问。

// graph.cpp

struct Edge {
    int from;
    int to;
    unsigned int id;
    Edge(): from(0), to(0), id(0) {};
};

struct Vertex {
    int label;
    vector<Edge> edge;
};

class Graph: public vector<Vertex> {
    int gid;
    unsigned int edge_size;
};

如果我在另一个文件中声明一个迭代器

bool get_forward_root (Graph &g, Vertex &v, vector<Edge*> &result) {
    for(vector<Edge>::iterator it = v.edge.begin(); it != v.edge.end(); it++) {
        if(v.label <= g[it->to].label)
        result.push_back(&(*it));
    }
}

据我了解,it可以看作是指针,因为 v.edge.begin()是第一个Edge vector<Edge> 中的对象, 但什么是 &(*it)

问题2。g有什么区别? , &g , *g

据我了解:

  • &g是内存地址。
  • *g是一个指向图对象的图指针,所以我们可以使用 Graph *g = new Graph();
  • g是一个图形对象

*g 和 g 的区别在于我们如何使用,例如这两个条件是相同的:

条件一:

Graph *g = new Graph();
g->gid = 0;

条件二:

Graph g;
g.gid = 0;

问题 3.

下面是什么意思?

Graph &g

以及为什么我们使用 g[it->to].label不是&g[it->to].label 非常感谢:)

最佳答案

Question 1: what is &(*it)

就像一个指针,但它不是指针。如果它是一个指针,&*it 将与 it 相同。在一般情况下,&(*it) 是迭代器it 指向的对象的地址(一个真正的指针)。我们可以在这里假设 & 运算符没有重载。

Question 2: What is the difference between g, &g, *g?

gg&g是g的地址。 *gg 指向的对象(如果 g 是指针)。你的 2 个条件(我不明白你为什么称它们为条件)做的事情几乎是一样的,是的。

Question 3: what is Graph &g?

这叫做引用。定义后,应立即对其进行初始化。将引用视为对象的另一个名称。 (更好的是,读一本书,见下文)。

您的所有问题都将在任何一本不错的 C++ 初学者书籍中得到详尽的解答。为此,我特别推荐 Lippman 的 C++ primer。寻找其他好书 here .

关于c++ - 使用指针的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567486/

相关文章:

c++ - 我们如何使用 C++ Lib Function 或 Windows API 在一个 session 中执行多个 cmd 命令?

c++ - MySQL 连接器/C++ PreparedStatement : forward declaration of ‘class sql::PreparedStatement’

c++ - c++类与OpenCV矩阵运算之间的转换

c++ - 从抽象类继承的类的实例

C++ 线程 : terminate called without an active exception

c++ - 如何为属性类实现通用访问器

c++ - 使用结构的全局 vector

c++ - 编译器如何解析函数?

c++ - 关于C++中的iterator和const问题

c++ - 如何获取 promise::set_exception(x) 的参数?