2014-03-29 83 views
0

这可能是也可能不是IDE特有的问题。在Code :: Blocks中获取范围错误

所以我做了一个使用Code :: Blocks的项目。在项目文件夹中有Main.cpp的,Person.h和Person.cpp:

// main.cpp 
#include "Person.h" 
int main() 
{ 
    int x = 1, y = 2, z = 3; 
    Person p = new Person(x, y, z); 
} 

我得到一个错误,指出人员和“p”在此范围内没有宣布。但是我在Person.h中声明了它们。我包含了Person.h头文件。那么,那里的代码也应该在Main中,对吧?

这里是Person.h的内容:

#ifndef PERSON_H 
#define PERSON_H 

class Person 
{ 
    public: 
      Person(); 
      Person(int, int, int); 
    private: 
      int x, y, z; 
}; 

#endif 
+0

你能证明什么的'Person.h'? – ryrich

回答

3

写里面的类构造函数。

Person(int a, int b, int c) 
{ 
    x=a; 
    y=b; 
    z=c; 
} 

,并更改

Person p = new Person(x, y, z); 

Person p(x, y, z); //if you just want to make an object p 

Person* p = new Person(x, y, z); //if you want a pointer p to point to a Person object 

//your code goes here 

//But in this case, you will have to explicitly deallocate the space you've allocated for p 
delete p; 
+0

不,将其更改为'Person p(x,y,z);'。据推测,构造函数的定义存在于Person.cpp中,但它应该使用构造函数初始值设定项列表。 – chris

+1

@chris'Person * p = new Person(x,y,z)'有什么问题? OP在这种模式下写下了这个问题,并且一定希望'p'是一个'指针'。 –

+0

因为它要求内存泄漏(注意OP代码中没有'delete')?在我看来,OP来自Java,只是想制作一个对象。 – chris