为什么我不能在班级中内联函数? [英] Why can I not inline a function in my class?

查看:96
本文介绍了为什么我不能在班级中内联函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过编写commons数据结构来学习c ++,并且有一个编译器警告我的内联add方法未定义.

I am learning c++ by writing commons data structures and I have a compiler warning that my inlined add method is not defined.

src/vector.h:10:14: warning: inline function 'Vector::add' is not defined
      [-Wundefined-inline]
        inline void add(const float val);

我做错了什么?据我所知,这些方法是匹配的.但是,如果我删除了内联方法,它可以正常工作,但是第一次调用add需要11380us,而第二和第三位大约是3667us,几乎是罚款成本的4倍.

What am I doing wrong? As far as I can tell the methods match up. However if I remove the inline method, it works fine but the first invocation of add takes 11380us but the 2nd and 3rd are around 3667us -nearly 4x penalty cost.

src/vector.h

src/vector.h

//#include <cstddef>

class Vector {
public:
    explicit Vector(const int n);
    explicit Vector(const int n, const float val);
    float& operator[](const int i);
    inline int const length();
    inline void fill(const float val);
    inline void add(const float val);
    inline float sum();
private:
    float* arr;
    int len;
};

src.vector.cpp

src.vector.cpp

#include "vector.h"
#include <iostream>
#include <algorithm>
#include "yepCore.h"
#include "yepMath.h"
#include "yepLibrary.h"
#include <cstdlib>

using namespace std;

inline void Vector::add(const float val)
{
    chrono::steady_clock::time_point start = chrono::steady_clock::now();   
    for (int i = 0; i < len; ++i) {
        arr[i] += val;
    }
    chrono::steady_clock::time_point end = chrono::steady_clock::now();
    cout << "yepp add took " << chrono::duration_cast<chrono::microseconds>(end - start).count()
              << "us.\n";
}

/**
template <>
void Vector<float>::add(const float val)
{
    chrono::steady_clock::time_point start = chrono::steady_clock::now();   
    yepCore_Add_V32fS32f_V32f(arr, val, arr, len);
    chrono::steady_clock::time_point end = chrono::steady_clock::now();
    cout << "yepp add took " << chrono::duration_cast<chrono::microseconds>(end - start).count()
              << "us.\n";

}
...

推荐答案

必须在标头中定义内联函数.如果未在头文件中定义它们,则无法内联该函数,因为调用者将没有该定义.

Inline functions must be defined in the header. If they are not defined in the header file, then the function cannot be inlined, because callers won't have the definition.

这篇关于为什么我不能在班级中内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆