c++ - C++ 命名空间中的内联函数

标签 c++ function linker namespaces

我正在写一个矩阵库。 我将我的类放在 namespace SLMath 中。 但由于内联函数,我收到了错误。

这些是我的文件..

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)" (?valuePtr@Mat4@SLMath@@QAEQBMXZ) referenced in function _main

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

最佳答案

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

7.1.2/4
An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case.

关于c++ - C++ 命名空间中的内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826142/

相关文章:

c++ - 构建Qt时出现编译器错误

c++ - iphlpapi/ifdef.h

r - 来自函数的消息被多次重复

swift - 使用函数的返回值 - Swift

c - 如何通过将各自的部分放在不同的位置来链接两个目标文件?

c++ - 找不到库,即使它在搜索路径上

c++ - C++ 中的 Langtons Ant(控制台)- 核心转储

c++ - 为什么将 "<<"运算符作为函数调用会导致 "ambiguous call"编译器错误?

javascript - 将多个参数传递给 React 中的函数

windows - 混合来自不同版本的 Visual Studio 的库时的运行时问题