成员访问差异

aha*_*ron 1 c++ operators operator-precedence

谁能告诉我(*ptr).field和之间有什么不同ptr->field?我知道它以某种方式连接到静态和动态链接,但我不知道它是什么.谁能告诉我不同​​的东西,并举个例子?

编辑:如果我有这个代码:

Point p;       //point is a class that derive from class shape 
Shape *s=&p; 
               //there is a diffrence if i write:

(*s).print();  //print is virtual func
s->print();    // the answers will not be the same, why?
Run Code Online (Sandbox Code Playgroud)

TNX!

Chr*_*ton 7

这与静态或动态链接无关.

请参阅C++的运算符优先级.在.具有比优先级较低*,所以实际上有相当之间的差异*ptr.fldptr->fld.例如,以下代码演示:

#include <iostream>

struct foo {
  int f;
};

int main() {
  struct foo *p = new struct foo;
  p->f = 42;
  std::cout << p->f << std::endl;
  std::cout << (*p).f << std::endl;
  // The following will not compile
  // std::cout << *p.f << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

正如约翰Knoeller指出的,ptr->fld是语法糖(*(ptr)).fld,但是是不一样的*ptr.fld,这实际上会评估为*(ptr.fld),可能不是你想要什么.

ptr->fld当你有一个指向结构的指针并想要访问其中包含的字段时,你会使用它. (*(ptr)).fld意思是同样的东西,但不是那么整洁.*strct.fld当你有一个结构而不是指向结构的指针时,你会使用它包含一个field(fld),它是你要取消引用的指针.案例ptr->fld如上所示.案例*strct.fld可以使用以下结构:

struct foo {
  int *fld;
}

struct foo f;
f.fld = new int;
*f.fld = 42;
Run Code Online (Sandbox Code Playgroud)