为什么我会重新定义类错误? [英] Why am I getting this redefinition of class error?

查看:190
本文介绍了为什么我会重新定义类错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码转储的歉意:

gameObject.cpp:

gameObject.cpp:

#include "gameObject.h"
class gameObject
{
    private:
    int x;
    int y;
    public:
    gameObject()
    {
    x = 0;
    y = 0;
    }

    gameObject(int inx, int iny)
    {
        x = inx;
        y = iny;
    }

    ~gameObject()
    {
    //
    }
    int add()
    {
        return x+y;
    }
};

gameObject.h:

gameObject.h:

class gameObject
{
    private:
    int x;
    int y;
    public:
    gameObject();

    gameObject(int inx, int iny);
    ~gameObject();
    int add();
};

错误:

||=== terrac, Debug ===|
C:\terrac\gameObject.cpp|4|error: redefinition of `class gameObject'|
C:\terrac\gameObject.h|3|error: previous definition of `class gameObject'|
||=== Build finished: 2 errors, 0 warnings ===|

我不知道怎么了.帮助吗?

I can't figure out what's wrong. Help?

推荐答案

您要在头文件中定义类,将头文件包含到* .cpp文件中,并再次定义类,因为第一个定义是由头文件拖动到翻译单元中.但是每个翻译单元只能使用一个gameObject类定义.

You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.

实际上,您无需再次定义类即可实现这些功能.实现如下功能:

You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:

#include "gameObject.h"

gameObject::gameObject(int inx, int iny)
{
    x = inx;
    y = iny;
}

int gameObject::add()
{
    return x+y;
}

这篇关于为什么我会重新定义类错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆