我有一个关于内联函数的问题。
#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()
时,编译器应该复制该函数并插入到 main 函数体中,因为它是 内联
。
所以,我有一个问题,为什么编译器没有给出变量 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/