读书人

:类模板与stdafx.h

发布时间: 2012-02-08 19:52:21 作者: rapoo

求助:类模板与stdafx.h
Foo.h:
---------------------------------------
#ifndef FOO
#define FOO

template <typename type>
class Foo
{
public:
void fun();
};

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

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

int main(int argc,char* argv[])
{
Foo <int> f;
return 0;
}
---------------------------------------
编译时出错:
错误2fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h "”?f:\其它\C++练习\include\Foo.cpp6
这个“#include "stdafx.h "”该放到什么地方呢?
如果Foo是一个类而非类模板,也就是说,Foo.h末尾没有“#include "Foo.cpp "”,那把“#include "stdafx.h "”放到Foo.cpp的开头就可以了.
可是在上面这个例子中,如果把“#include "stdafx.h "”放到Foo.cpp的开头,那有会出现新错误:
错误2fatal error C1083: 无法打开包括文件:“stdafx.h”: No such file or directoryf:\其它\c++练习\include\Foo.cpp1
这该怎么办呢?

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

template <typename type>
class Foo
{
public:
void fun();
};

template <typename type> //编译器需要推导,一般放头文件中
void Foo <type> ::fun() {}

#endif

---------------------------------------
test.cpp:
---------------------------------------
//#include "stdafx.h " 为什么要stdafx.h?除非开始创建工程选了mfc支持,在Setting-General 里选Not Using MFC
#include <Foo.h>

int main(int argc,char* argv[])
{
Foo <int> f;
return 0;
}

[解决办法]
模版的话没办法,只能放到同一个文件里,至少目前的编译器是如此

读书人网 >C++

热点推荐