访问对象的取消引用值的语法

Syntax for Accessing Dereferenced Values of an Object

本文关键字:语法 引用 取消 对象 访问      更新时间:2023-10-16

在以下代码中:

#include <iostream>
class Foo{
public:
int *a, *b;
}
Foo::Foo(int x, int y) : a( new int ( x ) ) , b( new int ( y ) )
{
}
Foo test(1,2);

如果我想定制存储在指针变量a中的取消引用的值,为什么要写:

std::cout << *test.a << std::endl; //method 1

而不是:

std::cout << test.(*a) << std::endl; //method 2

在我看来,我们正在访问a的未引用值,即*a,并且这是类Footest对象的成员变量,因此方法2在语法上感觉更正确。方法1(我认为是正确的方法(似乎取消了对整个test对象的引用。

需要*test.a而不是test.(*a)的原因是a本身不存在(从作用域的角度来看(。它是Foo的成员,因此要访问Foo::a,您需要test.a。然后将*应用于test.a,因为test.a是一个指针。