我已经阅读了关于“指针”的主题,但我仍然有一些疑问。
// 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?
g
是 g
。 &g
是g的地址。 *g
是 g
指向的对象(如果 g 是指针)。你的 2 个条件(我不明白你为什么称它们为条件)做的事情几乎是一样的,是的。
Question 3: what is
Graph &g?
这叫做引用。定义后,应立即对其进行初始化。将引用视为对象的另一个名称。 (更好的是,读一本书,见下文)。
您的所有问题都将在任何一本不错的 C++ 初学者书籍中得到详尽的解答。为此,我特别推荐 Lippman 的 C++ primer。寻找其他好书 here .
关于c++ - 使用指针的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567486/