函数'未在此范围内声明',但它是!不是吗?

时间:2011-06-16 15:53:41

标签: c++

  

'initPhysics'未在此范围内声明。

我尽可能简化了我的计划;这是:

helloworld.hpp

#ifndef HELLOWORLD_HPP
#define HELLOWORLD_HPP

class testWorld {
    public:
        testWorld() {}
        ~testWorld() {}
        void initPhysics();
};
#endif

HELLO.CPP

#include "helloworld.hpp"
#include <iostream>

using namespace std;

void testWorld::initPhysics() {
    cout << "Initiating physics..." << endl;
}

int main(int argc,char** argv) {
    cout << "Hello World!" << endl;
    testWorld* world;
    world = new testWorld();
    world<-initPhysics();
    return 0;
}

我使用命令编译

g++ -c hello.cpp

并获得错误

hello.cpp: In function ‘int main(int, char**)’:
hello.cpp:14:21: error: ‘initPhysics’ was not declared in this scope

为什么编译器看不到initPhysics的声明,即使我包含了helloworld.hpp?

6 个答案:

答案 0 :(得分:15)

应该是world->initPhysics(),而不是world<-initPhysics()

您的版本被读作表达式“world小于-1乘以全局函数initPhysics()的结果”,它是无法找到的全局函数。

虽然这显然是测试代码,但我只想指出,如果您使用new分配对象,则必须在某处显式delete

答案 1 :(得分:3)

world<-initPhysics()应为world->initPhysics()

答案 2 :(得分:3)

ptr 中指向-><-运算符(不是ptr->member!)作为“成员” “换句话说:它是实际指针的某种文字表示。所以在你的情况下它应该是

world->initPhysics(); // note the ->, not <-

然而,虽然这回答了你的问题,但还远远不够。您的代码还有其他几个问题。

  1. 无需先创建未初始化的指针,然后对其进行初始化。这很容易出错,你应该立即初始化它:

    testWorld* world = new testWorld();
    world->initPhysics();
    
  2. 请注意,在C ++中,使用new运算符创建的每个对象都需要使用delete运算符明确销毁:

    delete  world; // sounds scary, BTW
    
  3. 您似乎来自Java或C#等语言,其中一切都必须new。在C ++中,这不是真的。默认情况下,您应该在堆栈上创建对象,而不是在堆上创建对象:

    testWorld world;
    world.initPhysics();
    
  4. 但您的代码仍然存在问题。你现在拥有的是两相结构。作为类的用户,我需要记住在使用它的实例之前调用初始化函数。但这就是构造者的用武之地!构造函数应该完全初始化对象,以使其处于可用状态。您应该从构造函数调用初始化函数:

    testWorld() {initPhysics();}
    
  5. 物理学是世界不可分割的一部分,不应该作为事后补充添加。 :)

答案 3 :(得分:0)

您希望world->initPhysics();代替world<-initPhysics();

答案 4 :(得分:0)

world<-initPhysics();

在这里,你的箭头方向错误。你应该:

world->initPhysics();

答案 5 :(得分:0)

相关问题