2016-11-30 43 views
0

我是C++的新手,我正在嘗試啓動一個項目,每次創建ATM類的新實例時,它都將帳戶id設置爲1,並顯示當前帳戶ID。 這是我的代碼:我如何使用這些類?

// Bank ATM.cpp : Defines the entry point for the console application. 
#include "stdafx.h" 
#include "ATM.h" 


int main() 
{ 
    ATM abunch[15]; 
    for (int i = 0; i < 15; i++){ 
     abunch[i] = ATM(); 
    } 
    return 0; 
} 


//ATM.h 
#include "stdafx.h" 
#ifndef atm 
#define atm 
class ATM { 
    static int accountID; 

public: 
    ATM(); 
}; 
int ATM::accountID = 0; 
#endif 


//ATM.cpp 
#include "stdafx.h" 
#include "ATM.h" 
#include <iostream> 
ATM::ATM() { 
    ++accountID; 
    std::cout << accountID; 
} 

我收到以下錯誤信息: enter image description here

我在做什麼錯?

+1

移動'INT ATM ::帳戶ID = 0;'到.cpp文件 – AndyG

回答

0

因爲是在.h文件中聲明的,所以在類的外部,每次該文件包含在另一個文件中時都會進行全局聲明。你包括兩次;在main.cppATM.cpp中。這是一個禁忌。

聲明需要轉移到ATM.cpp

//ATM.h 
#include "stdafx.h" 
#ifndef atm 
#define atm 
class ATM { 
    static int accountID; 

public: 
    ATM(); 
}; 
int ATM::accountID = 0; // <--- remove this line 
#endif 


//ATM.cpp 
#include "stdafx.h" 
#include "ATM.h" 
#include <iostream> 
int ATM::accountID = 0; // <----put it here 
ATM::ATM() { 
    ++accountID; 
    std::cout << accountID; 
} 
+0

如果我不#包括頭到BankATM.cpp文件,它說: ATM上的「標識符未找到」。 –

+0

如果我把代碼放入ATM.cpp並不意味着我必須將ATM.cpp包含到BankATM.cpp中,這會促使編譯器不必要地複製代碼。 –

+0

@Dustin史密斯,我更新了我的答案。 – CAB