表达式必须具有类类型

adr*_*on3 74 c++ class new-operator

我已经用c ++编写了一段时间,当我尝试编译这个简单的代码片段时,我遇到了困难

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

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

  {
    A *a = new A();
    a.f(); // this doesn't
  }
}
Run Code Online (Sandbox Code Playgroud)

Kos*_*Kos 146

这是一个指针,所以请尝试:

a->f();
Run Code Online (Sandbox Code Playgroud)

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

A a;
a.f();
A& ref = a;
ref.f();
Run Code Online (Sandbox Code Playgroud)

如果您有指针类型,则必须先取消引用它以获取引用:

A* ptr = new A();
(*ptr).f();
ptr->f();
Run Code Online (Sandbox Code Playgroud)

a->b符号通常只是一个简写(*a).b.

关于智能指针的说明

所述operator->可以被重载,这是值得注意的是使用智能指针.当您使用智能指针时,您还可以使用->引用指向的对象:

auto ptr = make_unique<A>();
ptr->f();
Run Code Online (Sandbox Code Playgroud)


Seb*_*ach 13

允许分析.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}
Run Code Online (Sandbox Code Playgroud)

作为一般建议:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.
Run Code Online (Sandbox Code Playgroud)

根据经验:如果您需要自己管理内存,通常会有一个优先级管理者或替代品,可以遵循RAII原则.


Oza*_*ray 8

总结:而不a.f();应该是a->f();

在main中,您已将a定义为指向A的对象的 指针,因此您可以使用运算符访问函数.->

一种但不太可读的方式是(*a).f()

a.f()本来可以用来访问f(),如果a被声明为: A a;


Dar*_*con 6

a是一个指针.你需要使用->,而不是.