对内联函数的困惑
Confusion about inline function
我有一个关于内联函数的问题。
#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 函数体中,因为它是 inline
.
所以,我有一个问题,为什么编译器不给出变量 int i;
被重新声明的错误?
您似乎对作用域感到困惑。它们不在 "within the same" 范围
您可以在不同范围内声明多个同名变量。一个非常简单的例子如下:
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 语句将根本无法正常运行。
我有一个关于内联函数的问题。
#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 函数体中,因为它是 inline
.
所以,我有一个问题,为什么编译器不给出变量 int i;
被重新声明的错误?
您似乎对作用域感到困惑。它们不在 "within the same" 范围
您可以在不同范围内声明多个同名变量。一个非常简单的例子如下:
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 语句将根本无法正常运行。