2016-02-28 41 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