【问题标题】:Inline function in namespaces in C++C ++命名空间中的内联函数
【发布时间】:2016-06-19 23:08:52
【问题描述】:

我正在编写一个矩阵库。 我把我的类放在命名空间 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) 提供错误,因为它声明为内联?

【问题讨论】:

  • 您发布的代码中没有任何内容可能导致此问题。我猜你的构建过程没有将你的可执行文件与编译后的翻译单元链接起来。
  • 感谢您的回复.. 但是当我从函数 valuePtr() 中删除 inline 关键字时,它工作正常。
  • 我们一般将内联函数放在表头中。并非所有编译器都足够聪明,可以从一个 .cpp 文件内联到另一个。或者只在更高的优化级别上这样做。

标签: c++ function linker namespaces


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。但是“inline float operator()(uint8,uint8) 呢?我在头文件中声明它并在 other.cpp 文件中定义它并在 main 函数中使用它而没有任何错误。
  • @Ankitsinghkushwah 如果某些东西可以编译,并不意味着它是正确的。由于违反此要求的程序不会强制执行任何行为,因此您现在处于未定义行为的领域。一种可能的结果是一切似乎都运行良好。
  • 好的,那么我将从函数中删除那些内联关键字。非常感谢您对我的代码有任何其他建议吗?
猜你喜欢
  • 2020-04-10
  • 1970-01-01
  • 2020-02-19
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 2020-05-16
  • 2017-05-31
相关资源
最近更新 更多