2011-07-01 102 views
46

我have't编码在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 
a.f(); // "f has not been declared" 
system("pause"); 
} 
+0

说“这不行”的行实际上可以,让你的问题看起来很混乱。 – juanchopanza

回答

105

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

a->f(); 

基本上操作.(用于访问对象的字段和方法)上的对象和引用被使用,所以:

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

如果你有一个指针类型,你必须取消对它的引用首批获得一个参考:

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

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

+0

刚开始使用C++,仍然必须使它成为一种自动操作来确定是否使用指针或引用。在我的特殊情况下,我需要的只是一个参考,但由于某种原因,我通过了一个指针。无论如何,感谢您的明确解释! –

6

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

在主您已定义一个作为指针的对象,因此可以访问使用->操作者的功能。

a.f()可能已被用来访问f()的,如果一个被宣布为: A a;

4

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

11

允许分析。

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

作为一个经验法则:如果你需要在自己的管理内存,一般是superiour经理或提供已替代,一个跟随RAII原则。

相关问题