表达式必须具有类类型

问题描述:

一段时间以来我都没有用C ++编写代码,当我尝试编译这个简单的代码片段时被卡住了:

I have't coded in c++ for some time and I got stuck when I tried to compile this simple snippet:

class A
{
  public:
    void f() {}
};

int main()
{
  {
    A a;
    a.f(); // works fine
  }

  {
    A *a = new A();
    a.f(); // this doesn't
  }
}


它是一个指针,因此请尝试:

It's a pointer, so instead try:

a->f();

基本上是运算符(用于访问对象和引用使用对象的字段和方法),因此:

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

如果您使用的是指针类型,则必须先取消引用以获得引用:

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

a-&b; $ 表示法是通常只是(* a).b 的简写。

The a->b notation is usually just a shorthand for (*a).b.

operator-> 可以重载,这在智能指针中尤为明显。当您正在使用智能指针时>,那么您还可以使用-> 来引用指向的对象:

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();