我想创建一个链表。关于C++中的结构和指针
对于下面的代码:
struct sampleStruct
{
int a;
sampleStruct *next = NULL;
};
sampleStruct *sample = new sampleStruct;
是什么sample.next
和sample->next
之间的区别?
我想创建一个链表。关于C++中的结构和指针
对于下面的代码:
struct sampleStruct
{
int a;
sampleStruct *next = NULL;
};
sampleStruct *sample = new sampleStruct;
是什么sample.next
和sample->next
之间的区别?
好吧,以更完整的方式解释它。其他大多数人已经写道,只要你有指针,你必须使用' - >'。但你也可以用'。'来做到这一点,你必须尊重运营商的优先权。我们需要'*'来获取指针的内容,但是它的优先级比'。'低,所以你必须把它写入括号中以给它更高的优先级,所以当你想用' “。您对写道:
(*sample).next
,你看,这是一个复杂的语法,这样做在一个更简单的方法“ - >”进行了介绍。有了它,你可以用更舒适的方式编写代码。
所以这是等于这个例子,它看起来好多了。
sample->next
由于sample
是一个指针,因此无法通过.
而不是间接运算符->
访问数据成员。例如,这将不会编译:
sample.next; // error: member reference type 'sampleStruct *' is a pointer;
// maybe you meant to use '->'?
该错误实际上是说明自己。
为什么你不试试然后找出? – 2013-04-07 11:21:33
其中只有一个会编译:) – dasblinkenlight 2013-04-07 11:22:38
请参阅http://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c – 2013-04-07 11:25:40