Reputation: 347
Recently I have been making a game in C++ and I have ran into trouble when trying to use inheritance.
What I'm trying to do is create cars and a player which is also some form of a car. Both of those things require an x and y position, a method to get those and a render. Since I want the code to have a good quality, I wanted to only write that code once. I did part of that in the following Entity file: http://pastebin.com/nceanyQD
And the Entity header: http://pastebin.com/CLTv9B0Y
Then I have this in the Car header: http://pastebin.com/T9v0WGKd
And finally this in the Car file: http://pastebin.com/CJ5wnby5
When I run this code it will give several errors. First of all in the Player.h right under the Entity line telling me: Entity base class undifined.
Another error in a Game file (which renders and updates everything) in the following code:
Car Game::getCarAtLocation(int x, int y)
{
vector<Car>::iterator iter = cars.begin();
for(iter = cars.begin(); iter != cars.end(); ++iter)
{
if(iter->getX() == x)
{
if(iter->getY() == y)
{
return *iter;
}
}
}
return NULL;
}
It tells me getY and getX is not a member of Car. However, the same getY and getX do work totally fine in the operator<< overload in the Car file itself.
Finally the last error I'm getting in the Entity.h file is 'class' type redifinition.
What am I doing wrong and how do I fix it?
If there is any other code required, it can be downloaded here. https://dl.dropboxusercontent.com/u/59067404/BalCab.zip
Upvotes: 0
Views: 131
Reputation: 720
Second error is simple - iterator must be "const", because getY() and getX() has const modifier.
vector<Car>::const_iterator iter = cars.begin();
In class Car in overload operator<< works because Car argument "const"
friend ostream& operator<<(ostream& os, const Car car);
And why in Car.cpp change signature of overloaded operator you write:
ostream& operator<<(ostream& os, Car car) ......
must be same as declaration
ostream& operator<<(ostream& os, const Car car)
Upvotes: 2
Reputation: 379
Add include guards to your header files or put
#pragma once
at the beginning of the headers
Entity.h file is 'class' type redifinition.
means that the compiler is presented with the the text
class Entity { [...] };
more than once.
You can think of an include statement as a copy-paste. Everything you write in
file.h
will be copy-pasted into any file that has the statement
#include "file.h"
when you call the compiler (press the build/make button in your IDE)
If your source file now has
#include "Car.h"
#include "Entity.h"
the definition the compiler will now have two copies of your Entity definition.
Upvotes: 1