2016-03-06 62 views
0

我在写一个矩阵库。 我把我的类放在命名空间SLMath中。 但由于内联函数我得到错误。C++中命名空间中的内联函数

这些都是我的文件..

Mat4.hpp

#ifndef INC_SLMATH_MAT4_H 
#define INC_SLMATH_MAT4_H 


#include<cstdint> 
#include<algorithm> 

namespace SLMath 
{ 
    class Mat4 
    { 
     typedef std::uint8_t uint8; // You know that Its tedious to write   std::uint8_t everytime 
     float matrix[16]; 
     inline int index(uint8 row,uint8 col) const; 

    public: 

     //Constructors 
     Mat4(); 
     Mat4(const Mat4 &other); 

     //Destructor 
     ~Mat4(); 

    //operators 
    void operator=(const Mat4 &other); 

    //loads the identity matrix 
    void reset(); 

    //returns the element in the given index 
    inline float operator()(uint8 row,uint8 col) const; 

    //returns the matrix array 
    inline const float* const valuePtr(); 

}; 
} 


#endif 

和Mat4.cpp ..

#include"Mat4.hpp" 


namespace SLMath 
{ 

//private member functions 
inline int Mat4::index(uint8 row,uint8 col) const 
{ 
    return row*4+col; 
} 


//Public member functions 
Mat4::Mat4() 
{ 
    reset(); 
} 


Mat4::Mat4(const Mat4 &other) 
{ 
    this->operator=(other); 
} 


Mat4::~Mat4(){} 


inline float Mat4::operator()(uint8 row,uint8 col) const 
{ 
    return matrix[index(row,col)]; 
} 


void Mat4::reset() 
{ 
    float identity[16] = 
    { 
     1.0,0.0,0.0,0.0, 
     0.0,1.0,0.0,0.0, 
     0.0,0.0,1.0,0.0, 
     0.0,0.0,0.0,1.0 
    }; 

    std::copy(identity,identity+16,this->matrix); 
} 


void Mat4::operator=(const Mat4 &other) 
{ 
    for(uint8 row=0 ; row<4 ; row++) 
    { 
     for(uint8 col=0 ; col<4 ; col++) 
     { 
      matrix[index(row,col)] = other(row,col); 
     } 
    } 
} 


inline const float* const Mat4::valuePtr() 
{ 
    return matrix; 
} 

} 

但是当我做这个..

SLMath::Mat4 matrix; 
const float *const value = matrix.valuePtr(); 
主要功能

它给我一个链接错误.. 。

Main.obj : error LNK2019: unresolved external symbol "public: float const * __thiscall SLMath::Mat4::valuePtr(void)" ([email protected]@[email protected]@QAEQBMXZ) referenced in function _main 

和当我从函数valuePtr()中删除内联关键字。它工作正常。 请帮我... 还有一件事是不清楚的是,如果编译器给函数valuePtr()赋予错误,那么它也应该给operator()(uint8,uint8)赋予错误,因为它的声明为内联?

+0

您发布的代码中没有任何内容会导致此问题。我猜你的构建过程并没有将你的可执行文件与编译好的翻译单元连接起来。 – StoryTeller

+0

谢谢你的回应..但是当我从函数valuePtr()中删除内联关键字时,它的工作正常。 –

+2

我们通常将内联函数放在标题中。并非所有编译器都足够聪明,可以从一个.cpp文件内联到另一个.cpp文件。或者只在更高的优化级别上做到这一点。 –

回答

5

内联函数应该是定义为在每个使用它的TU中。这意味着您不能将声明放入头文件中并在实现文件中定义函数。

7.1.2/4
内联函数应每翻译单元,其中它是ODR使用的,并应具有完全相同在每种情况下相同的定义来限定。

+0

谢谢你的回答。但是怎么样“inline float operator()(uint8,uint8)?我在一个头文件中声明了它,并将它定义在other.cpp文件中,并在main函数中使用它,没有任何错误。 –

+1

@Ankitsinghkushwah如果编译的东西没有这意味着它是正确的,因为违反这个要求的程序没有规定行为,你现在处于未定义行为的领域,其中一个可能的结果是,一切似乎都完美地工作。 –

+0

好吧,然后我将删除那些来自函数的内联关键字非常感谢你和任何其他关于我的代码的建议? –