2016-03-06 63 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

好吧,然後我將刪除那些來自函數的內聯關鍵字非常感謝你和任何其他關於我的代碼的建議? –