Reputation: 3
Any help on why I am getting a 'C2011 'Transaction':'class' type redefinition
? I'm sure it's glaringly obvious but I cannot for the life of me figure it out. Please help.
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;
}
Upvotes: 0
Views: 474
Reputation: 1518
You can either use a header guard in the header file which will make sure you never ever more than once define a class or struct etc. in any other cpp file.
To add a header guard you can simply do this:
#ifndef TRANSACTION_H
#define TRANSACTION_H
// your header file
#endif
Or simply add
#pragma once
to all your header files and you're good.
Upvotes: 5
Reputation: 234875
You need to use include guards in transaction.h
:
#if !defined(your_symbol)
#define your_symbol 1
/*ToDo - code here*/
#endif
Where, your_symbol
is typically an embellishment of the name of the file. Be careful not to use a leading double underscore or a single leading underscore followed by a capital letter as they are reserved symbols.
This prevents the class declaration from being included more than once in any compilation unit.
You can use #ifndef your_symbol
in place of my first line, and drop the 1 from the second line, or perhaps even just use a #pragma once
directive at the top of the file, but the version I present works on every compiler I've ever come across.
Upvotes: 2
Reputation: 3456
In your header try this:
#ifndef TRANSACTION //If transaction has never been defined before
#define TRANSACTION //Define transaction
//Content of your header
#endif
This header guard will probably help you. Indeed it will prevent your header from being included multiple times which leads to redefinitions. If you include your header just once you don't need these guards, but it doesn't hurt to have them anyway.
Alternatively, you can use #pragma once
at the beginning of your header.
If you want to read more about them, check wikipedia
Upvotes: 0