c++ - 内联在基类主体内声明但通过派生类调用的函数

标签 c++ inheritance inline

情况是这样的。我有一个在头文件中声明的基类,其中包含一些 protected 数据成员和一些公共(public) getter 函数(单行主体)。没有虚拟方法。从它派生出一个子类,并定义了自己的构造函数,其定义放在对应的cpp文件中。

是否会内联通过派生类的对象调用 getter 函数?

编辑:这是我的代码。

// quad.h
class QuadratureRule {
protected:
  int ngauss;
  Array points;
  Array weights;
public:
  QuadratureRule(int ng) : ngauss(ng) { }
  double getweights(int ig) const {
    return weights[ig];
  }
};
class Quadrature2D : public QuadratureRule {
public:
  Quadrature2D(int ng);
};

//quad.cpp
#include "quad.h"
Quadrature2D::Quadrature2D(int ng) : QuadratureRule(ng) {
  // initialize arrays in a certain way
}

我希望 getweights 在被 Quadrature2D 类的对象调用时内联。 另外,我使用的是 GCC g++ 5.4 和 6.3。

最佳答案

编辑:

我一直在检查它,似乎如果你打开优化,它实际上会被内联。但正如人们已经在评论中所说,这实际上取决于实现。示例:

Code without optimizations

Code with optimizations


你让我很好奇,所以我查了一下。 这是我的程序:

// base.h
include <iostream>

class Base {
    int x;
    int y;
public:
    Base(int x = 0, int y = 0) : x(x), y(y) {}
    int getx() const { return x; }
    void setx(int x) { this->x = x; }
    int gety() const { return y; }
    void sety(int y) { this->y = y; }
};

和:

// derived.cpp
#include "base.h"

class Derived : public Base {
    int z;
public:
    Derived(int x = 0, int y = 0, int z = 0) : Base(x, y), z(z) {}
};

using namespace std;

int main() {
    Derived d(1, 2, 3);
    cout << "d.x == " << d.getx() << ", d.y == " << d.gety() << endl;
    d.setx(4);
    d.sety(4);
    cout << "d.x == " << d.getx() << ", d.y == " << d.gety() << endl;
    return 0;
}

在 gcc 6.3 上编译:

g++ -Wall -Werror -g -pedantic-errors -o derived derived.cpp

这是 objdump 的一部分,在 main() 中:

a2b:   e8 1a 01 00 00          call   b4a <_ZN4Base4setxEi> ; A call to setx()
a30:   48 8d 45 e0             lea    rax,[rbp-0x20]
a34:   be 04 00 00 00          mov    esi,0x4
a39:   48 89 c7                mov    rdi,rax
a3c:   e8 33 01 00 00          call   b74 <_ZN4Base4setyEi> ; A call to sety()
a41:   48 8d 45 e0             lea    rax,[rbp-0x20]
a45:   48 89 c7                mov    rdi,rax
a48:   e8 15 01 00 00          call   b62 <_ZNK4Base4getyEv> ; A call to gety()
a4d:   89 c3                   mov    ebx,eax
a4f:   48 8d 45 e0             lea    rax,[rbp-0x20]
a53:   48 89 c7                mov    rdi,rax
a56:   e8 df 00 00 00          call   b3a <_ZNK4Base4getxEv> ; A call to getx()

假设我没有忽略任何重要的事情,我猜你不能相信你的代码是内联的。

关于c++ - 内联在基类主体内声明但通过派生类调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42601039/

相关文章:

c++ - 性能 : typedef vs wrapper class for primitive types?

c++ - 将十六进制数转换为 bool 数组

c++ - 如何使用链表和单项类C++实现多项式类

c# - 多个显式接口(interface)实现

c# - 每个继承的类的C#静态实例成员

c++ - 内联函数和类以及头文件

c++ - map 的开始迭代器不起作用 C++

c++ - 两百万以下的素数之和。埃拉托色尼筛法

java - 在 Java 中,如果子类用实例子变量隐藏静态父变量,那么继承方法将使用哪个变量?

.cpp 文件中的 C++ 内联成员函数