表达式必须具有类类型 [英] Expression must have class type

查看:345
本文介绍了表达式必须具有类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来我都没有用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();

这篇关于表达式必须具有类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆