2015-11-02 20 views
0

任何幫助,爲什麼我得到'C2011 'Transaction':'class' type redefinition?我相信這顯而易見,但我不能爲我的生活弄清楚。請幫忙。C++類重新定義錯誤 - 我無法弄清楚爲我的生活

transaction.h

#include <string> 

class Transaction 
{ 
private: 
    int amount; 
    std::string type; 

public: 
    Transaction(int amt, std::string kind); 
    std::string Report(); 
}; 

transaction.cpp

#include "transaction.h" 

using namespace std; 

Transaction::Transaction(int amt, std::string kind):amount(amt), type(kind) 
{ 
} 

string Transaction::Report() 
{ 
    string report; 
    report += " "; 
    report += type; 
    report += " "; 
    report += to_string(amount); 

    return report; 
} 
+0

'transaction.h'裏面有什麼? – vaultah

+0

這是問題的頂部,在//transaction.h之後 –

+1

在transaction.h中需要一個[include guard](http://stackoverflow.com/questions/8020113/c-include-guards)。 –

回答

5

您可以使用頭文件的標題後衛,這將確保你永遠不會超過一次定義任何其他CPP文件類或結構等。

要添加頁眉後衛,你可以簡單地這樣做:

#ifndef TRANSACTION_H 
#define TRANSACTION_H 
// your header file 
#endif 

或者簡單地添加

#pragma once 

您所有的頭文件,你是好。

+0

感謝您的幫助Linus;非常感激。 –

+0

沒有看到你先在評論中給出了答案。 Upvote給予兩種可能性 – LBes

0

在你的頭試試這個:

#ifndef TRANSACTION //If transaction has never been defined before 
#define TRANSACTION //Define transaction 
//Content of your header 
#endif 

這個頭文件保護可能會幫助你。事實上,它會阻止你的標題被多次包含,從而導致重新定義。如果你只是在你不需要這些守衛時加入你的頭部,但是無論如何也不會傷害他們。

或者,你可以在你的頭的開始使用#pragma once

如果您想了解更多關於他們,檢查wikipedia

1

您需要使用包括警衛transaction.h

#if !defined(your_symbol) 
#define your_symbol 1 
/*ToDo - code here*/ 
#endif 

其中,your_symbol通常是文件名的點綴。注意不要使用前導雙下劃線或單引號下劃線,後跟大寫字母,因爲它們是保留符號。

這可以防止類聲明在任何編譯單元中被多次包含。

您可以使用#ifndef your_symbol來代替我的第一行,並從第二行刪除1,或者甚至可以在文件的頂部使用#pragma once指令,但是我提供的版本適用於每個編譯器,曾經遇到過。

相關問題