Having two classes reference each other.
Hello! I'm new to the forums and C++ as well. I've been following through a few books but I haven't found how to do this correctly yet.
I'm programming a console application using Visual C++.
What I am aiming to do is to allow one class to reference another. This is for a game that me and couple of friends are programming.
I found a thread similar to this before I joined. However following through it I haven't produced any reliable results. So, here is my code, split up into 5 files.
The code compiles fine. However, in the linking stage, I recieve several errors:
Code:
Linking...
a.obj : error LNK2005: "public: __thiscall A::A(void)" (??0A@@QAE@XZ) already defined in cppsample.obj
a.obj : error LNK2005: "public: __thiscall A::~A(void)" (??1A@@QAE@XZ) already defined in cppsample.obj
a.obj : error LNK2005: "public: int __thiscall A::getBV(void)" (?getBV@A@@QAEHXZ) already defined in cppsample.obj
b.obj : error LNK2005: "public: __thiscall B::B(void)" (??0B@@QAE@XZ) already defined in cppsample.obj
b.obj : error LNK2005: "public: __thiscall B::~B(void)" (??1B@@QAE@XZ) already defined in cppsample.obj
b.obj : error LNK2005: "public: int __thiscall B::getAV(void)" (?getAV@B@@QAEHXZ) already defined in cppsample.obj
Release/cppsample.exe : fatal error LNK1169: one or more multiply defined symbols found
cppsample.cpp
Code:
//This is the main file.
//Includes (Unused)
/*
These include files are not included but may be included later.
#include <limits> //Limits
#include <fstream> //File stream for dealing with files.
*/
//Includes (Standard)
#include <cstdio> //C Standard Input/Output
#include <cstdlib> //C Standard Library
#include <iostream> //Input/Output Stream
#include <string> //C++ Strings
using namespace std; //Use Standard Namespace
//Includes (custom)
#include "a.cpp"
#include "b.cpp"
//Defines
#define CURRENT_EXPERIMENT "This program will try to get two classes to reference each other."
//Type Definitions
typedef short unsigned int sui; //Shorthand form of numbers from 0 to 65,535.
typedef short int si; //Shorthand form of numbers from -32,768 to 32,767.
int main(int iNumberOfArgs, char* psArgs[])
{
cout << CURRENT_EXPERIMENT << "\n";
system("PAUSE");
A hi;
cout << hi.iOfA << "\n";
system("PAUSE");
return 0;
}
a.cpp
Code:
#include "a.h"
#include "b.h"
A::A()
{
iOfA=1;
pToB=0;
}
A::~A()
{
}
int A::getBV()
{
return pToB->iOfB;
}
b.cpp
Code:
#include "a.h"
#include "b.h"
B::B()
{
iOfB=2;
pToA=0;
}
B::~B()
{
}
int B::getAV()
{
return pToA->iOfA;
}
a.h
Code:
#ifndef A_ADDED
#define A_ADDED
#ifndef B_ADDED
class B;
#endif
class A
{
public:
A();
~A();
int getBV();
int iOfA;
private:
B* pToB;
};
#endif
b.h
Code:
#ifndef B_ADDED
#define B_ADDED
#ifndef A_ADDED
class A;
#endif
class B
{
public:
B();
~B();
int getAV();
int iOfB;
private:
A* pToA;
};
#endif