expression式必须有类的types

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

#include "iostream" using namespace std; class A { public: void f() { cout<<"f()\n"; } }; int main() { // A a; //this works A *a = new A(); //this doesn't af(); // "f has not been declared" system("pause"); } 

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

 a->f(); 

基本上是运营商. (用于访问对象的字段和方法)用于对象和引用,所以:

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

如果你有一个指针types,你必须先取消引用来获得一个引用:

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

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

允许分析。

 #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 af(); // "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. 

作为一个经验法则:如果你需要自己pipe理记忆,那么通常有一个高级经理或其他可用的select,一个遵循RAII原则。

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

主要定义一个指向A 对象的指针,所以你可以使用->操作符访问函数。

如果a被声明为: af()可能已经被用来访问f() A a;

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