c++ - 关于内联函数的困惑

标签 c++ function inline

我有一个关于内联函数的问题。

#include <iostream>
using namespace std;

class A 
{
public:
    inline void fun()
    {
        int i=5;
        cout<<i<<endl;
    }
};

int main() 
{
    A a1;
    int i = 2;
    a1.fun();
    cout<<i<<endl;
    return 0;
}

在上面的程序中,当调用函数 fun() 时,编译器应该复制该函数并插入到 ma​​in 函数体中,因为它是 内联

所以,我有一个问题,为什么编译器没有给出变量 int i; 被重新声明的错误?

最佳答案

您似乎对范围感到困惑。它们不在“同一范围内”

您可以在不同范围内声明多个具有相同名称的变量。一个非常简单的例子如下:

int main()
{
    int a;       // 'a' refers to the int until it is shadowed or its block ends
    { 
        float a; // 'a' refers to the float until the end of this block
    }            // 'a' now refers to the int again
}

内联扩展不是纯文本替换(与宏相反)。

函数是否内联对语义没有影响,否则程序的行为会根据函数是否内联而有所不同,并且 return 语句根本无法正常运行。

关于c++ - 关于内联函数的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45903416/

相关文章:

c++ - 在不重绘顶点的情况下纹理化三角地形

c++ - 使用我自己的 list.sort() 逻辑,试图模拟其他来源,为什么我会收到看似正确格式的错误?

php - 如何在 while 循环中连接表中的两列值,如 -product_name(product_quantity), ..... 并存储在变量中

c - 如何调用传递给另一个函数的任意 C 函数?

c++ - 在 QWidgets 线程实例上运行 lambda 函数槽

c++ - 找出数组中出现次数最少的数

r - 动态创建函数和表达式

html - 如何将 div 插入到文本将与其内联的 div

java - Java 中的内联对象实例化和转换

css - 如何找到 element.style 的来源?即哪个 JS 或 jQ 文件正在注入(inject)它。我想修复,而不是覆盖