2012-09-21 71 views
1

我對C++代碼有很多麻煩,但我不明白爲什麼。連接靜態類和朋友函數時奇怪的錯誤

我正在開發一個包含myclass.h和myclass.cpp的靜態庫libmylib.a。

我遇到的問題是這樣的:

// myclass.h 
class myClass{ 
    public: 
     myclass(); 
     myclass(a,b); 

    // some methods. 

    private: 
    int a ; 
    int b ; 
}; 

在myclass.cpp我定義構造函數方法等等等等,一切工作正常: 我能夠使用該庫在我的main.cpp代碼。

我加入好友功能:

// myclass.h 
class myClass{ 
    public: 
     myclass(); 
     myclass(a,b); 
     friend void foo() ; 

    // some methods. 

    private: 
    int a ; 
    int b ; 
}; 

我定義foo的功能myclass.cpp這樣

// myclass.cpp 
void foo(){ 
    cout << "In foo function " ; 
} 

的問題是,如果我嘗試在主要使用FOO()的.cpp我得到,指出編譯錯誤:

//main.cpp 
#include "myclass.h" // foo() is declared here! 

foo() ; 

main.cpp:62:6: error: ‘foo’ was not declared in this scope

現在我真的不明白問題在哪裏。 我注意到,添加好友功能後,似乎鏈接器不再使用mylib了,但我不明白爲什麼。此外,這很奇怪,因爲如果我在main.cpp myclass中註釋foo()並且它的方法可以毫無問題地使用。

我在做什麼錯?我花了兩個小時試圖弄清楚,但真的不明白!

解決方案:按照答案的建議:

// myclass.h 
void foo() ; // the function has to be declared outside the class 

class myClass{ 
    public: 
     myclass(); 
     myclass(a,b); 
     friend void foo() ; // but here you have to specify that 
          // is a friend of the class! 
    // some methods. 

    private: 
    int a ; 
    int b ; 
}; 
+0

您是否已經聲明瞭'foo()'函數?或者在調用點之前定義了'foo()'函數? – Mahesh

+0

是的,我有。這是在myclass.h – lucacerone

+0

@LucaCerone是否在課外宣佈**?或者只是作爲朋友? –

回答

2

這不是一個鏈接器錯誤,它是一個編譯器錯誤。編譯器告訴你它不知道如何調用函數foo,因爲它缺少它的定義或聲明。

將函數聲明爲朋友不能替代正確的聲明。當你說foo是一位朋友時,你也不會將foo引入到範圍中。從某種意義上說,友誼宣言是你的職業從外部看不到的私人細節。

爲了在C++中使用函數,您需要首先聲明它。這通常通過與實現文件相對應的頭文件完成,但您可以這樣做:

void foo();

如果foo在同一個文件中main定義,你可以提前main的移動foo來解決這個問題(看到第一次使用前的功能定義與編譯器OK)。

+0

正如我在問題中所解釋的,foo()在myclass.h中聲明爲朋友函數。該定義在myclass.cpp中給出。 – lucacerone

+0

@LucaCerone友誼宣言是你的班級從外部看不到的私人細節。你需要正確地聲明你的功能。請參閱編輯。 – dasblinkenlight

+0

感謝這工作!我將編輯測試以顯示具體示例的解決方案! – lucacerone

0

你有沒有使用它之前宣佈foo

#include "header_where_foo_is_declared.h" 
int main() 
{ 
    foo(); 
} 

void foo(); 
int main() 
{ 
    foo(); 
} 

???

+0

是的,我做了..我解釋了聲明是在myclass.h中完成的 – lucacerone

+0

@LucaCerone是否在課堂外聲明?或者只是作爲朋友? –