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

究竟应该怎么"在头文件中声明,在源文件中定义"

2012-02-27 
究竟应该如何在头文件中声明,在源文件中定义?Foo.h:---------------------#ifndefFOO#defineFOOclassFoo

究竟应该如何"在头文件中声明,在源文件中定义"?
Foo.h:
---------------------
#ifndef   FOO
#define   FOO

class   Foo
{
public:
        void   fun();
};
----------------------
Foo.cpp:
----------------------
#include   "Foo.h "

void   Foo::fun()   {}
----------------------
test.cpp:
----------------------
#include   "Foo.h "

int   main()
{
        Foo   f;
        f.fun();
        return   0;
}
-----------------------
链接时出错.

[解决办法]
Foo.h:
---------------------
#ifndef FOO
#define FOO

class Foo
{
public:
void fun();
};

#endif
----------------------
Foo.cpp:
----------------------
#include "Foo.h "

void Foo::fun() {}
----------------------
test.cpp:
----------------------
#include "Foo.h "

int main()
{
Foo f;
f.fun();
return 0;
}
-----------------------

g++ -o foo.o foo.cpp
g++ -o test.o test.cpp
g++ -o test test.o foo.o
[解决办法]
:)
[解决办法]
放在一个头文件里就可以了,的确带模板的不能分开。
[解决办法]
去看C++ primer上关于模板分别编译。

//1. Foo.h:
---------------------
#ifndef FOO
#define FOO
template <typename type>
class Foo
{
public:
void fun();
};
#include "Foo.cpp " //注意:这里
#endif
----------------------
//2. Foo.cpp:
----------------------
#ifndef _FOO_CPP_
#defind _FOO_CPP_ //加上这个防止重复编译

#include "Foo.h "
template <typename type>
void Foo <type> ::fun() {}

#endif
----------------------
test.cpp:
----------------------
#include "Foo.h "

int main()
{
Foo <int> f;
f.fun();
return 0;
}
-----------------------

热点排行