[email protected][email protected]#$:~/cpp/OOP/6$ g++ -o main main.o NormalAccount.o HighCreditAccount.o Account.o AccountHandler.o
AccountHandler.o:(.bss+0x0): multiple definition of `AccountHandler::account_number'
main.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
我收到了上面的錯誤消息。 但我無法找到它的多重定義的代碼,所以我改變了所有ACCOUNT_NUMBER到number_of_account在「account.h」和「AccountHandler.cpp」 和奇怪的多重定義錯誤
[email protected][email protected]#$:~/cpp/OOP/6$ vi AccountHandler.cpp
[email protected][email protected]#$:~/cpp/OOP/6$ g++ -c AccountHandler.cpp
[email protected][email protected]#$:~/cpp/OOP/6$ g++ -o main main.o NormalAccount.o HighCreditAccount.o Account.o AccountHandler.o
[email protected][email protected]#$:~/cpp/OOP/6$
它編譯好。
在那之後,我改變了的main.cpp有點
[email protected][email protected]#$:~/cpp/OOP/6$ g++ -c main.cpp
[email protected][email protected]#$:~/cpp/OOP/6$ g++ -o main main.o NormalAccount.o HighCreditAccount.o Account.o AccountHandler.o
AccountHandler.o:(.bss+0x0): multiple definition of `AccountHandler::number_of_account'
main.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
和錯誤消息再次出現。
我在所有的頭文件中使用的#ifndef的#define #define和 當我AccountHandler.cpp和accounthandler.h改變的變量,它再次編譯好, 所以我不知道爲什麼會發生
這裏驗證碼:
#ifndef __ACCOUNTHANDLER_H__
#define __ACCOUNTHANDLER_H__
#include "account.h"
class AccountHandler
{
private:
Account* account[100];
static int number_of_account;
public:
AccountHandler(){}
void show_menu();
void make_account();
void deposit_money();
void withdraw_money();
void show_all_account_info();
~AccountHandler();
};
int AccountHandler::number_of_account=0;
#endif
什麼是'AccountHandler :: account_number'(或'AccountHandler :: number_of_account')?你如何申報?你如何定義它?最重要的是,你在什麼地方定義它?你需要向我們展示一些代碼,否則幾乎不可能在沒有猜測的情況下回答這個問題。 – 2013-04-26 10:29:21
標題保護僅防止在單個翻譯單元中包含多個包含(並因此包含多個定義)。如果您在頭文件中定義了一個全局對象,那麼您將在每個包含該頭文件的翻譯單元(cpp)中定義它(使用它定義一個定義規則)。您可以使用內部鏈接('static')定義對象,或者僅將其聲明爲「extern」,並在一個翻譯單元中定義。 – jrok 2013-04-26 10:32:36
@jrok:由於它看起來是一個靜態類成員,所以不能給它內部鏈接,或者在聲明中使用'extern'。如果它在命名空間範圍內,那麼給它內部連接幾乎肯定是一件錯誤的事情,因爲你將在每個翻譯單元中獲得單獨的副本;這至少可以說是令人困惑的。 – 2013-04-26 10:47:49