I've googled, searched, tried different things, and I'm stuck. Learning C++, and one of the exercises is to pass a struct to a function. I've done that, but I am now trying to pass it to a function contained in a header file. I get these errors and I don't quite understand how to fix it.
adStruct.cpp:7:8: error: redefinition of 'struct Advertizing'
In file included from C:\Users\james\Desktop\NoteP_C++\adStruct.cpp:2:0:
dailyIncome.h:5:8: error: previous definition of 'struct Advertizing'
You need to understand what happens when you include a file. The entire contents of the include file are placed in the .cpp file as if the 2 had been concatenated. Hence the compiler errors.
A better way of doing things is to make the Advertizing struct a class, with the findDailyIncome function being a class function. In C++ struct & class are almost the same thing, the only difference is that structs have public access by default.
#ifndef _ADVERTIZING_H
#define _ADVERTIZING_H
class Advertizing {
private:
int m_adShown; //A convention to start member names with m_
float m_userClickPercent;
float m_avgPerClick;
float m_dailyIncome;
public:
Advertizing(); //default constructor - you can overload this to take arguments to build the obj
~Advertizing(); //default destructor - leave this as is
Advertizing(int adShown, float userClickPercent, float m_avgPerClick ); //initialises member variables
findDailyIncome();
};
#endif
The .cpp file has the code for each member function:
#include <iostream>
#include "Advertizing.h" //use the class name for naming files
usingnamespace std; //this is bad, it pollutes global namespace with heaps of things from std
//do this instead:
using std::cin;
using std::cout;
using std::endl;
//or put std:: before each std thing
int main (){
Advertizing user1; //the object
//input variables
int adShown = 0;
float userClickPercent 0.0;
float avgPerClick = 0.0;
float dailyIncome = 0.0;
cout << "How many ads did you show today?" << endl;
cin >> adShown;
cout << "What percentage of users clicked on ads?" << endl;
cin >> userClickPercent;
cout << "What was the average earned per click?" << endl;
cin >> userClickPercent;
//call constructor
user1(adShown, userClickPercent, userClickPercent);
user1.dailyIncome = dailyIncome(user1);
cout << "Todays income is " << user1.dailyIncome() << endl;
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
Hope this helps, and you can see how organised it is. Some important points are that there is no code in the header file, so it can be reused in lots of places without causing chaos.