我目前正在通过阅读一本名为"21天自学C"的好初学者的书来学习C(我已经学习了Java和C#,所以我的动作速度要快得多).我正在阅读有关指针的章节,而 - >(箭头)操作符出现时没有解释.我认为它用于调用成员和函数(比如.(点)运算符,但是用于指针而不是成员).但我不完全确定.我可以获得解释和代码示例吗?
我试图围绕C与Objective-C中的使用和语法的一些差异.特别是,我想知道C运算符和Objective-C中的点运算符和箭头运算符的使用方式有何不同(以及原因).这是一个简单的例子.
C代码:
// declare a pointer to a Fraction
struct Fraction *frac;
...
// reference an 'instance' variable
int n = (*frac).numerator; // these two expressions
int n = frac->numerator; // are equivalent
Run Code Online (Sandbox Code Playgroud)
Objective-C代码:
// declare a pointer to a Fraction
Fraction *frac = [[Fraction alloc] init];
...
// reference an instance variable
int n = frac.numerator; // why isn't this (*frac).numerator or frac->numerator??
Run Code Online (Sandbox Code Playgroud)
那么,看看frac两个程序中的相同情况(即它是指向Fraction对象或结构的指针),为什么它们在访问属性时使用不同的语法?特别是,在C中,numerator可以访问属性frac->numerator,但是使用Objective-C,可以使用点运算符访问它frac.numerator.既然frac是两个程序中的指针,为什么这些表达式不同?任何人都可以帮我澄清一下吗?