2013-07-18 176 views
7

我有一個奇怪的問題,當我在類A中創建一個靜態函數,我想從類B函數調用它。我得到未定義的引用靜態函數

未定義的參考`A :: FuncA的(INT)」

這裏是我的源代碼: a.cpp

#include "a.h" 

void funcA(int i) { 
    std::cout << i << std::endl; 
} 

#ifndef A_H 
#define A_H 

#include <iostream> 

class A 
{ 
    public: 
     A(); 
     static void funcA(int i); 
}; 

#endif // A_H 

b.cpp

#include "b.h" 

void B::funcB(){ 
    A::funcA(5); 
} 

和b.h

#ifndef B_H 
#define B_H 
#include "a.h" 

class B 
{ 
    public: 
     B(); 
     void funcB(); 
}; 

#endif // B_H 

我與代碼:: Blocks的編制。

回答

14
#include "a.h" 

void funcA(int i) { 
    std::cout << i << std::endl; 
} 

應該

#include "a.h" 

void A::funcA(int i) { 
    std::cout << i << std::endl; 
} 

由於funcA是你A類的靜態函數。此規則適用於靜態和非靜態方法。

+0

謝謝,這正是問題所在。 我以爲funcA()是靜態的,寫A :: funcA()就沒有任何意義......看來我錯了。 – xenom

6

你忘了前綴類名的定義:

#include "a.h" 

void A::funcA(int i) { 
    ^^^ 
//Add the class name before the function name 
    std::cout << i << std::endl; 
} 

你沒有的東西,你定義無關funcA(),兩個函數結束了的方式(即A::funcA()funcA(),前者是不確定的) 。

+0

謝謝,這是問題所在。當Nbr44回答第一個問題時,我要驗證他的答案,但是要高舉你的答案。 – xenom