首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

内联函数解决思路

2012-04-25 
内联函数声明内联函数如下:test.hclass Point2D{public:inline float get_x() const...}test.cpp中实现in

内联函数
声明内联函数如下:

test.h
class Point2D
{
  public:
  inline float get_x() const;
...
}

test.cpp中实现
inline float Point2D::get_x() const
{
  return x_;
}

在main.cpp中调用
Point2D o2D(1,1);
cout<<o2D.get_x();

编译器报错:
test.h:20: warning: inline function `float Point2D::get_x() const' used but neve
r defined
g++ -O3 -o main test.o test_main.o
test_main.o:test_main.cpp:(.text+0x13f): undefined reference to `Point2D::get_x(
) const'

实在是不明白啊,请教于各位大侠


[解决办法]
内联函数应该定义到头文件中。
这样在调用的地方才能见到函数体,从而完成“内联”。
[解决办法]
内联函数的实现要放去.H里面
[解决办法]

探讨

应该这样解释,内联是在编译的时候完成的,在此期间不会查看.cpp,因为.cpp的内容是在link时完成的,这样解释对么?

[解决办法]
探讨
应该这样解释,内联是在编译的时候完成的,在此期间不会查看.cpp,因为.cpp的内容是在link时完成的,这样解释对么?

[解决办法]
探讨
引用:
应该这样解释,内联是在编译的时候完成的,在此期间不会查看.cpp,因为.cpp的内容是在link时完成的,这样解释对么?


应该这样解释吧,由于main.cpp引用只是test.h,在编译时main.cpp仅能看到get_x()的函数声明,而得不到该函数的定义,因此无法在main.cpp中将内联函数进行展开,形成副本

[解决办法]
We can specify that a member is inline as part of its declaration inside the class body. Alternatively, we can specify inline on the function definition that appears outside the class body. It is legal to specify inline both on the declaration and definition. One advantage of defining inline functions outside the class is that it can make the class easier to read.


[解决办法]
探讨
必须放到.h里吗?

[解决办法]
Inline 函数不一定要定义在.h里啊!
只要加了关键字inline就可以了,无非就是可读性的问题嘛,从对错来分析没有问题啊

还有LZ要搞清楚啦!定义在类声明之中的成员函数将自动地成为内联函数!
你不用+inline的!它也是内联函数!
定义内联函数的过程仅仅是想编译器提交一个申请,

inline fun() {};这一句是指你向编译器请求希望把这个函数定义成内联函数,但它不一定能成为内联函数!如果函数中出现for循环,switch语句等,那么编译器将拒绝你的请求,那么函数不会被定义成内联函数!

定义内联函数仅仅是一个善意的请求,而不是一个强制的命令!决定权在编译器本身!约定因素是函数内部有没有过于复杂的语句,如果你来个函数自调用,那肯定不行的!但不会出错,只是你的函数不是inline,而是普通的函数!

热点排行