向前声明类的问题

时间:2015-01-25 05:05:14

标签: c++ class debugging

所以我试图在我的C ++项目中声明一个类,然后在main中创建它。

所以我有player_obj.cpp,它包含类,classes.h用于声明类,main.cpp用于它。

classes.h

#ifndef CLASSES_H
#define CLASSES_H

class player_class
{
    public:

        int x;
        int y;
        char sprite;
        int xprevious;
        int yprevious;

    private:

        bool active;

    public:

        void update_xy();
        player_class(int _x, int _y, char _sprite);
        void step();
        void destroy();
};

#endif

的main.cpp

#include <iostream>
#include "classes.h"
using namespace std;

int main()
{
    player_class player_obj (5,5,'#');
    cout << player_obj.x << ", " << player_obj.y << endl;
    return 0;
}

和player_obj.cpp

#include <iostream>
#include <Windows.h>
using namespace std;

class player_class
{
    public:

        //Coordinates
        int x;
        int y;

        //Sprite
        char sprite;

        //Previous coordinates
        int xprevious;
        int yprevious;

    //Not everyone can set the activity
    private:

        //Active
        bool active;

    //Update xprevious and yprevious - Called by the step event
    void update_xy()
    {
        xprevious = x;
        yprevious = y;
    }

    //All functions public  
    public:

        //Create event/Constructer
        player_class(int _x, int _y, char _sprite)
        {
            //Set default variables
            x = _x;
            y = _y;
            sprite = _sprite;
            xprevious = x;
            yprevious = y;
            active = true;
        }

        //Step event
        void step()
        {
            //Update old xprevious and yprevious
            update_xy();

            //Do other stuff here

        }

        //Drestroy event
        void destroy()
        {
            active = false;
        }
};

我认为这样可行,但是当我编译并运行它时,我得到:

main.cpp:(.text+0x2c): undefined reference to`player_class::player_class(int, int, char)'

我做过一些研究,但我似乎无法解决这个问题。

我非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

嗯,你有点接近,你头上的内容确实是一个类声明(不是前瞻性声明)。

问题是你从未定义过它。你在player_obj.cpp中所拥有的是对类重新定义的憎恶,但你已经宣布了你的类。只需包含头文件并逐个定义功能即可完成!

    #include "classes.h"

    player_class::player_class(int _x, int _y, char _sprite)
    {
        //Set default variables
        x = _x;
        y = _y;
        sprite = _sprite;
        xprevious = x;
        yprevious = y;
        active = true;
    }

    // and so on

如果您认真学习现代C ++,请注意以下几点:

  • #pragma once是保护头文件的现代方法。不要使用那些#ifdef..#endif构造。
  • 一般来说,不要以下划线开头的任何名称。尤其不是作为公共合同一部分可见的参数。
  • 你有类初始化器是有原因的,请使用它们!在构造函数中,您不需要半个复制粘贴变量的屏幕。

答案 1 :(得分:0)

你不想要前瞻声明。你想要一个声明。这是在头文件中声明类并在cpp文件中定义其函数的经典案例。然后包括你想要使用你的班级的标题

当您想要使用指向该类的指针作为某个函数或成员变量的参数时,您只需要前向声明,但该类的定义尚不可用。 请注意,当您转发声明一个类时,您不能在该标头中使用此类的成员变量或函数

-regards 高塔姆

相关问题