c++ - 成员(member)权限差异

标签 c++ operators operator-precedence

谁能告诉我 (*ptr).fieldptr->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?

TNX!

最佳答案

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

参见 C++'s operator precedence . . 的优先级低于 *,所以 *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;
}

正如 John Knoeller 指出的那样,ptr->fld(*(ptr)).fld 的语法糖,但与 * 不同ptr.fld,实际上计算结果为 *(ptr.fld),可能不是您想要的。

当您有一个指向结构的指针并想访问其中包含的字段时,您可以使用ptr->fld(*(ptr)).fld 意思相同,但不那么整洁。当你有一个结构而不是指向结构的指针时,你会使用 *strct.fld,它包含一个字段 (fld),这是一个你想要取消引用的指针. ptr->fld 的情况如上所示。 *strct.fld 的大小写可以与以下结构一起使用:

struct foo {
  int *fld;
}

struct foo f;
f.fld = new int;
*f.fld = 42;

关于c++ - 成员(member)权限差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1971202/

相关文章:

c++ - 通过 C++ 程序更改 shell 的目录

c++ - 如何以及何时执行静态链接 (MinGW)?

c++ - 使用 std::enable_if 有什么问题?

php - $variable[] 和 array_push($variable, $newValue) 哪个更快?

c++ - 运算符 < 和 > 如何与指针一起使用?

ruby - 这个串联的运算顺序是什么?

c++ - 解决 "expression must have pointer to class type"错误

c++ - OpenGL 的子弹物理

c - 为什么以下 C 代码中的后递减运算符没有按预期工作? (具有 7 的值)

javascript - JavaScript 中的 && 和 == 运算符优先级重要吗?