内联函数于非内联函数的区别

njjn 2003-01-15 05:42:02


class Rectangle{
int width,height;
public:
Rectangle(int w=0,int h=0);
int getwidth() const;
void setwidth(int w);
int getheight() const;
void setheight(int h);

};
inline Rectangle::Rectangle(int w,int h):width(w),height(h){}
inline int Rectangle::getwidth() const{return width;}
inline void Rectangle::setwidth(int w){width=w;}
inline int Rectangle::getheight() const{return height;}
inline void Rectangle::setheight(int h){height=h;}
void main(){
Rectangle r(19,47);
int iheght=r.getheight();
r.setheight(r.getwidth());
r.setwidth(r.getheight());

}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

class Rectangle{
int width,height;
public:
Rectangle(int w=0,int h=0);
int getwidth() const;
void setwidth(int w);
int getheight() const;
void setheight(int h);

};
Rectangle::Rectangle(int w,int h):width(w),height(h){}
int Rectangle::getwidth() const{return width;}
void Rectangle::setwidth(int w){width=w;}
int Rectangle::getheight() const{return height;}
void Rectangle::setheight(int h){height=h;}
void main(){
Rectangle r(19,47);
int iheght=r.getheight();
r.setheight(r.getwidth());
r.setwidth(r.getheight());

}

请叫各位 这到底有什么区别
可否加入输出语句看看结果的不同
我自己加的结果也没什么区别?


解释的清楚明白就立即给分

谢谢
...全文
300 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
chinajiji 2003-01-15
  • 打赏
  • 举报
回复

////这是inline的汇编码:
int iheght=r.getheight();

mov eax, DWORD PTR _r$[ebp+4]
mov DWORD PTR _iheght$[ebp], eax

////这是非inline的汇编码,注意这里有call语句,而inline函数没有, 这个call语句就会带来函数调用开销;
int iheght=r.getheight();

lea ecx, DWORD PTR _r$[ebp]
call ?getheight@Rectangle@@QBEHXZ ;Rectangle::getheight
mov DWORD PTR _iheght$[ebp], eax

如果你指定某个函数为inline,但编译器有可能不生成inline,在这种情况下,有的编译器会给出警告信息.
eion 2003-01-15
  • 打赏
  • 举报
回复
内联函数是函数与#define之间的一种折中

内联函数比一般函数块,因为它一般采用于#define一样的将代码嵌入,而不是函数调用。
大家知道函数调用要有一定的开销(如调用前的压栈,调用后的弹栈等),而#define就仅仅是代码的替换


#define AAA 123ad

void main()
{
int AAA;
};

那么给出警告的在int AAA; 处而不会在#define AAA处,因为此处仅仅是代码的替换

又如
#define for if (0); else for
void main()
{
for (int i=0; i<100; i++)...;
for (int i=0; i<10; i++)...;
}
用这样的替换后再VC中就没有编译错误了

但是#define有它内在地缺点:不能检查语法的错误,所以我们既要加快程序执行速度,又要尽可能保证我们的程序少出错,所以有了内联函数。

内联函数也是“代码嵌入”,而不是函数的“函数调用”,所以速度快
内联函数是一类特殊的函数,所以,它依照函数的规则编写,可以检查语法,却依照#define模式将代码嵌入,用来提高速度

所以,用VC时你在内联函数(inline)内如果有循环的话,它会给你警告:你的内联已经没有太大的意义了。
chinajiji 2003-01-15
  • 打赏
  • 举报
回复
从结果上是看不出来区别的,你可以生成源程序的汇编码查看,inline函数没有call语句,非inline函数有call语句.
rushman 2003-01-15
  • 打赏
  • 举报
回复
从结果上是看不出来区别的。(能看到的只是两者的速度不同)

调用内联函数时,实际上并不是调用,而是将内联函数的代码(不是源代码,是目标代码)插入到调用函数中。这样就没有调用的入栈出栈等等过程,从速度上要比一般的非内联函数要快。

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧