谁能告诉我 (*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?
TNX!
最佳答案
这与静态或动态链接无关。
参见 C++'s operator precedence . .
的优先级低于 *
,所以 *ptr.fld
和 ptr->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/