I apologise if this seems like more than one question but...
In my rpg text adventure project, I'm having trouble knowing where to put all the game objects.
I've got a Location class and a Weapons class, and I was going to create the weapon objects so that their positions can be linked to the locations. This led me to think I had to create ALL the weapon objects, of which there may be dozens, which will be quite a lot of data, with each one having it's own data members with descriptions etc.
What I wanted to do was instantiate all the objects in a separate file. I thought it could go in the Weapon.cpp file after the class stuff, but my main .cpp can't acces the data. This may be the completely wrong way of doing it, so I'm all ears!
So
1. Can you only put function declarations and definitions in .h and .cpp files? If yes, then where do I put all the non function objects if I don't want them in my main.cpp file?
2. If I can put them in, then how does it work? I've included everything in the right places, but I just get undefined identifier errors. I thought that if the files are include in main.cpp, then they are as good as being actually in the same file.
As a side note, I am very new to c++, so am only using things I currently understand, but I am deliberately making the game complex because it's the way I learn the best :)
This is an example of what I was trying to do, not my actual code. In main on line 18, rat2 is undefined, even though the file it's defined in is included.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// Pet.h
#pragma once
class Pet
{
private:
int m_age;
string m_colour;
public:
Pet(int, string);
int Age();
string Colour();
};
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// Pet.cpp
#include "stdafx.h"
#include "Pet.h"
Pet::Pet(int age, string colour) :
m_age(age),
m_colour(colour)
{}
int Pet::Age() { return m_age; };
string Pet::Colour() { return m_colour; };
Pet rat2(1, "black"); // main.cpp can't see this.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// main.cpp
#include "Pet.h"
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//Pet rat2(1, "black"); // This works if un-commented
int main()
{
Pet rat(2, "white");
cout << rat.Colour << endl;
cout << rat2.Colour << endl; // doesnt work, "rat2" unidentified
return 0;
}
|