【发布时间】:2014-09-06 19:18:16
【问题描述】:
int num1 = 8; //okay
int *pointer; //okay
*pointer = &num1; //NOT okay, compiler says (Error:a value of type int* cannot be
//assigned to an entity of type "int")
int num2 = 8; //okay
int *pointer = &num2; //okay
我很困惑为什么第一部分给出错误而第二部分没有,它们在我看来是一样的
【问题讨论】:
-
改成
pointer = &num1,因为pointer的类型是int*,&num1的类型也是int*(而*pointer的类型是int)。 -
*和&根据上下文有不同的含义。在声明中它们表示指针类型和引用类型,在表达式中它们是操作符的解引用和地址 -
int *pointer = X;表示:int *pointer; pointer = X;
标签: c++ pointers declaration