C++ INLINE 关键词

黎 浩然/ 4 5 月, 2022/ C/C++, 计算机/COMPUTER/ 0 comments

类方法内联

class A {
public:
    void f1(int x);
    /*
     * @brief 类内实现的函数都是内联函数;类外实现的函数想成为内联函数必须在实现处加 inline。
     *
     * @param x
     * @param y
     */
    void Foo(int x,int y) { ///< 类内实现的函数都是隐式内联函数!
    };
    void f1(int x); ///< 类外实现的函数想成为内联函数必须在实现处加inline关键字。
};
#include <iostream>
#include "inline.h"
using namespace std;

/**
 * @brief inline要起作用要与函数实现放在一起,inline是“用于实现的关键字,不是用于声明的关键字”
 *
 * @param x
 * @param y
 *
 * @return
 */
int Foo(int x,int y); // 函数声明 

inline int Foo(int x,int y) {    
    // 函数实现
    return x+y; 
}

// 实现处加inline关键字,推荐这种写法实现函数内联! 
inline void A::f1(int x ){}

int main(){
    cout<<Foo(1,2)<<endl;
}
/**
 * 编译器对 inline 函数的处理步骤
 * 将 inline 函数体复制到 inline 函数调用点处
 * 为所用 inline 函数中的局部变量分配内存空间
 * 将 inline 函数的的输入参数和返回值映射到调用方法的局部变量空间中 
 */

虚函数初步

# include <iostream>
# include <vector>
using namespace std;

class Animal {
public:
    virtual void eat() const { 
        cout << "I eat like a generic Animal." << endl; 
    }
    virtual ~Animal() {}
};

class Wolf : public Animal {
public:
    void eat() const { cout << "I eat like a wolf!" << endl; }
};

class Fish : public Animal {
public:
    void eat() const { cout << "I eat like a fish!" << endl; }
};

class GoldFish : public Fish {
public:
    void eat() const { cout << "I eat like a goldfish!" << endl; }
};

class OtherAnimal : public Animal {};

int main() {
    std::vector<Animal*> animals;
    animals.push_back( new Animal() );
    animals.push_back( new Wolf() );
    animals.push_back( new Fish() );
    animals.push_back( new GoldFish() );
    animals.push_back( new OtherAnimal() );
    for( std::vector<Animal*>::const_iterator it = animals.begin();
       it != animals.end(); ++it) {
        (*it)->eat();
        delete *it; 
    }
    return 0; 
}

想要实现为虚函数,只需要在父类的函数定义中加virtual(会被继承)!

INLINE与虚函数

#include <iostream>
using namespace std;

class Base {
public:
    virtual void who() {
        cout << "I am Base\\n";
    }
    virtual ~Base() {}
};

class Derived : public Base {
public:
    void who(){ // 不写inline时隐式内联 
        cout << "I am Derived\\n";
    } 
};

int main() {
    // 编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
    Base b;
    b.who();
    // 此处的虚函数是通过指针调用的,呈现多态性,需要在运行时期间才能确定,所以不能为内联
    Base *ptr = new Derived();
    ptr->who();
    // 会先调用派生类(Derived)析构函数,再调用基类(Base)析构函数,防止内存泄漏 delete ptr;
    ptr = nullptr;
    system("pause");
    return 0; 
}
Share this Post

Leave a Comment

您的邮箱地址不会被公开。 必填项已用 * 标注

*
*