2016-02-28 43 views
1

我想这段代码错误LNK2005同时实现升压函数指针

demo.hpp

#include <boost/function.hpp> 
#include <boost/bind.hpp> 

using namespace std; 

typedef boost::function<int(int,int)>func; 

class funcPointer 
{ 
public: 

    void add_call(func); 
}; 

demo.cpp

#include <iostream> 
#include "demo.hpp" 

void funcPointer::add_call(func f) 
{ 
    cout << "Result of add: " << f(5,7) <<endl; 
} 

的main.cpp

#include "demo.cpp" 

int add(int x,int y) 
{ 
    cout << "x: " << x <<endl; 
    cout << "y: " << y <<endl; 

    return x + y; 
} 

int main() 
{ 
    funcPointer *fun = new funcPointer; 

    fun->add_call(boost::bind(add, _1, _2));  

    return 0; 
} 

编译时我得到了f更正错误:

demo.obj : error LNK2005: "public: void __thiscall funcPointer::add_call(class boost::function<int __cdecl(int,int)>)" ([email protected]@@[email protected][email protected]@[email protected]@@Z) already defined in main.obj 
E:\vs_c++\boost_func_ptr\Debug\boost_func_ptr.exe : fatal error LNK1169: one or more multiply defined symbols found 

我不明白这是什么样的错误,有人可以帮我解决这个错误吗?

回答

2

不要#include源文件!

在你的情况(我只是在这里猜测)文件demo.cpp是该项目的一部分,所以它被编译并链接到创建可执行文件。问题在于,由于您还将该源文件作为头文件包含在内,因此该函数也在main.cpp中定义。

main.cpp中,您应该包含标头文件demo.hpp

+0

Thanx Joachim,它的工作 – NIXIN