Reputation: 2270
I have a struct
Inside myStructure.h
struct myStructure
{
int myInteger;
double myDoublesArray[4];
char myCharArray[79];
};
Inside myClass.h
#include "myStructure.h"
class myClass
{
private:
myStructure myStruct[4]
private:
Prog1Class();
~Prog1Class();
void setMyStructData();
};
Inside main.cpp
#include<iostream>
#include <string>
#include "myClass.h"
#include "myStructure.h"
using namespace std;
void myClass::setMyStructData()
{
for(int i = 0; i < 5 ; i++)
{
cout << "Please enter an integer: " << endl;
cin >> myStruct[i].myInteger;
for(int j = 0; j< 5; j++)
{
cout << "Please enter a double: ";
cin >> myStruct[i].myDoublesArray[j];
}
cout << endl << "Please enter a string: ";
cin.ignore(256, '\n');
cin.getline(myStruct[i].myCharArray, 79, '\n');
}
}
int main(void)
{
setStructData();
cin.get()
}
The errors i'm getting are " 'myStructure' : 'struct' type redefinition " , and " left of '.myInteger' must have class/struct/union "
I'm sure it's some simple mistake I've made with the structure, but I've looked around and everything seems to be correct to my noob eyes. Thanks!
And this isn't homework. I'm just trying to get back into programming, and understanding how some different things work, and I'm doing old assignments from other schools. Thanks.
Upvotes: 0
Views: 334
Reputation: 9648
You are getting multiple definitions because you include the structure header in both the myClass.h
and main.cpp
. You want to use include guards: https://en.wikipedia.org/wiki/Include_guard.
Also in your main()
you are trying to access a private member function without having an instance of the class. There are a few issues here. First you need an instance. However you cannot create an instance in main because the constructor is private as well. Your myClass.h
should look like this:
class myCLass
{
private:
myStructure myStruct[4]
public: // NOTE public here
Prog1Class();
~Prog1Class();
void setMyStructData();
};
Then in main you can create a myClass
:
myClass c;
And then you can call the member function on c
(because I changed it to public, otherwise you still would not be allowed to call it):
c.setMyStructureData();
Upvotes: 1
Reputation: 153840
Your key problem is that you don't have include guards: when including the same header multiple times the compiler sees the same definition multiple times and doesn't like that! You need to guard against that, typically using macros, e.g.:
// myStructure.h
#ifndef INCLUDED_MYSTRUCTURE
#define INCLUDED_MYSTRUCTURE
// struct definition goes here
#endif
(likewise for all other headers).
Upvotes: 4