在向我的struct添加构造函数时不断收到链接器错误

时间:2014-01-17 01:40:51

标签: c++ struct linker linker-errors

所以这个文件编译得很好。如果我决定将构造函数添加到我的默认对象,我会收到链接器错误。

#ifndef VERTEX_FORMATS_H_
#define VERTEX_FORMATS_H_

#include "../utilities/float3.h" (this file does not have other includes within it)
#include "../utilities/float2.h" (this file does not have other includes within it)

struct VERTEX_PARTICLES
{
    float3 v3fPosition;     //has a default constructor that set its own values to zero
    float3 v3fVelocity;     //has a default constructor that set its own values to zero
    float3 v3fAcceleration; //has a default constructor that set its own values to zero
    float fCurLife;
    float fEndLife;
    float fCurScale;
    float fStartScale;
    float fMidScale;
    float fEndScale;
    unsigned int uiColor; 

    VERTEX_PARTICLES( void );
};


VERTEX_PARTICLES::VERTEX_PARTICLES( void ) :
    fCurLife( 0.0f ), fEndLife( 0.0f ),
    fCurScale( 0.0f ), fStartScale( 0.0f ),
    fMidScale( 0.0f ), fEndScale( 0.0f ),
    uiColor( 0U ) { }

#endif

如果删除构造函数,文件编译就好了,但是有一个构造函数会给我链接器错误:

  

VERTEX_PARTICLES :: VERTEX_PARTICLES(void)“(?? 0VERTEX_PARTICLES @@ QAE @ XZ)已在Game.obj中定义

我猜这是在抱怨其他地方我不止一次添加这个文件?但是我认为这不是一个问题,因为我#defined我的对象,而且没有构造函数也不会给我带来问题。

2 个答案:

答案 0 :(得分:1)

除非是内联的,否则无法在标题中定义它。您定义它的方式,每次包含文件时都会被拾取。

我应该这样建造:

struct VERTEX_PARTICLES
{
    float3 v3fPosition;     //has a default constructor that set its own values to zero
    float3 v3fVelocity;     //has a default constructor that set its own values to zero
    float3 v3fAcceleration; //has a default constructor that set its own values to zero
    float fCurLife;
    float fEndLife;
    float fCurScale;
    float fStartScale;
    float fMidScale;
    float fEndScale;
    unsigned int uiColor; 

    VERTEX_PARTICLES( void ) :
        fCurLife( 0.0f ), fEndLife( 0.0f ),
        fCurScale( 0.0f ), fStartScale( 0.0f ),
        fMidScale( 0.0f ), fEndScale( 0.0f ),
        uiColor( 0U ) { }
};

答案 1 :(得分:1)

在:

#ifndef VERTEX_FORMATS_H_
#define VERTEX_FORMATS_H_

不能防止构造函数VERTEX_PARTICLES::VERTEX_PARTICLES( void )的多个“实现”:

例如,如果您有2个cpp文件,则都使用#include "vertex_formats.h"

两者都包含头部,你将有2个构造函数的实现,因此它将被编译两次,链接器找到2个相同的命名定义。