表达式必须具有类类型


82

我已经有一段时间没有用C ++编写代码了,当我尝试编译这个简单的代码片段时,我陷入了困境:

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

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

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

2
实际上,这行没错,这使您的问题看起来很混乱。
juanchopanza 2011年

Answers:


165

它是一个指针,所以尝试:

a->f();

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

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

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

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

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

关于智能指针的说明

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

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

刚开始使用C ++时,仍然必须使其自动确定是否使用指针或引用。在我的特定情况下,我所需要的只是一个引用,但是由于某种原因,我改为传递了一个指针。无论如何,感谢您的明确解释!
Guillaume M

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.
}

作为一般建议:

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.

根据经验:如果您需要自己管理内存,通常已经有一个超级管理员或替代管理员可用,它遵循RAII原则。


9

摘要a.f();应该代替它a->f();

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

一种但不太易读的方法是(*a).f()

a.f()如果a被声明为: A a;


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.