|
在TCPL里面有介绍可以把类成员函数声明成inline从而提高运行时效率。如第10章的例子:
- class Date {
- public:
- int day() const;
- // ...
- private:
- int d, m, y;
- }
- inline int Date::day const { return d; }
复制代码
但是发现如果将函数声明和定义分开写在.h和.cc里面,虽然能编译成模块,但是却无法链接。
如以下例子:
- // test.h
- #ifndef _TEST_H_
- #define _TEST_H_
- class test {
- public:
- test();
- test(int);
- void show() const;
- private:
- int i;
- }
- #endif
- // test.cc
- #include <iostream>
- #include "test.h"
- using namespace std;
- test::test()
- : i(0)
- {
- }
- test::test(int _i)
- : i(_i)
- {
- }
- inline void show() const
- {
- cout << i << endl;
- }
- // main.cc
- #include "test.h"
- int main()
- {
- test t(10);
- t.show();
- }
复制代码
在使用
$ g++ -c test.cc
$ g++ -c main.cc
时没有问题,但是在链接时
$ g++ -o test main.o test.o
会报错:
main.o(.text+0x35): In function `main':
main.cc: undefined reference to `test::show() const'
但是如果将类成员定义一起写进.h文件,即不把test.cc单独编译就没有问题。不声明成inline也没问题……
不知道怎么回事?难道将类成员函数声明成inline就不能单独编译成模块了吗?请各位多指教! |
|