I have 4 files car.cpp, car.h, motorvehicle.h and vehicle.h. I am programming in the QT-creator environment.
The issue i am having is:
error: out-of-line definition of 'getSafetyRating' does not match any declaration in 'vehicle::Car'
int Car::getSafetyRating()
Here are the program files for reference, i am new to learning c++ and would really appreciate the help! Cheers Alex. I Apologies in advance for any repost of problems if any.
vehicle.h
#ifndef VEHICLE_H
#define VEHICLE_H
#include <string>
namespace vehicle
{
class Vehicle
{
public:
Vehicle(int numberOfPassengers,
int topSpeed,
int numberOfWheels,
std::string color = "red");
virtual ~Vehicle();
virtual std::string getColor();
virtual int getTopSpeed();
virtual int getNumberOfWheels();
virtual int getNumberOfPassengers();
virtual int getSafetyRating() = 0;
protected:
int m_numberOfPassengers;
int m_topSpeed;
int m_numberOfWheels;
std::string m_color;
};
}
#endif // VEHICLE_H
motorvehicle.h
#ifndef MOTORVEHICLE_H
#define MOTORVEHICLE_H
#include "vehicle.h"
namespace vehicle
{
class MotorVehicle : public Vehicle
{
public:
MotorVehicle(int numberOfPassengers,
int topSpeed,
int numberOfWheels,
double kilometresPerLitre);
MotorVehicle(int numberOfPassengers,
int topSpeed,
int numberOfWheels,
std::string color,
double kilometresPerLitre);
virtual ~MotorVehicle();
virtual double getKilometresPerLitre();
protected:
double m_kmpl;
};
}
#endif // MOTORVEHICLE_H
car.h
#ifndef CAR_H
#define CAR_H
#include "motorvehicle.h"
namespace vehicle
{
class Car : public MotorVehicle
{
public:
Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
int numberOfAirBags = 2,
bool abs = true,
int numberOfWheels = 4);
Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
std::string color,
int numberOfAirBags = 2,
bool abs = true,
int numberOfWheels = 4);
virtual ~Car();
virtual int getNumberOfAirBags();
virtual bool hasAutomaticBreakingSystem();
protected:
int m_numberOfAirBags;
int m_abs;
};
}
#endif // CAR_H
car.cpp
#include "car.h"
using namespace vehicle;
Car::Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
int numberOfAirBags,
bool abs,
int numberOfWheels) :
MotorVehicle(numberOfPassengers, topSpeed, numberOfWheels, kilometresPerLitre),
m_numberOfAirBags(numberOfAirBags),
m_abs(abs)
{
}
Car::Car(int numberOfPassengers,
int topSpeed,
double kilometresPerLitre,
std::string color,
int numberOfAirBags,
bool abs,
int numberOfWheels):
MotorVehicle(numberOfPassengers, topSpeed, numberOfWheels,color, kilometresPerLitre),
m_numberOfAirBags(numberOfAirBags),
m_abs(abs)
{
}
Car::~Car()
{
}
int Car::getNumberOfAirBags()
{
return m_numberOfAirBags;
}
bool Car::hasAutomaticBreakingSystem()
{
return m_abs;
}
int Car::getSafetyRating()
{
int SafetyRating = 0;
if (m_numberOfAirBags >= 4)
{
SafetyRating += 3;
}
else if (m_numberOfAirBags >= 2)
{
SafetyRating += 2;
}
else if (m_numberOfAirBags > 0)
{
SafetyRating += 1;
}
if (m_abs)
{
SafetyRating += 2;
}
return SafetyRating;
}
Your car class does not have a getSafetyRating declared in the .h file, and the pure virtual function in vehicle requires it. When you declare something pure virtual, ie func() = 0, you basically say that any class that inherits from it MUST implement this function.
So both the motor vehicle class, and the car class must at the very least declare the getSafetyRating function.
One thing that should solve this is to add this to Motor Vehicle:
virtual int getSafetyRating() = 0;
and in the car.h write
virtual int getSafetyRating()
Add declaration of function int getSafetyRating() in your car.h
Related
I am making a school assignment, but I am getting a strange error. I have tried to google it, but nothing helped.
So I have a file called main.cpp. Within this file I have some includes and code.
This:
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
#include "RentalAdministration.h"
#include "Limousine.h"
#include "Sedan.h"
void addTestDataToAdministration(RentalAdministration* administration)
{
string licencePlates[] = {"SD-001", "SD-002", "SD-003", "SD-004", "LM-001", "LM-002"};
for (int i = 0; i < 4; i++)
{
Car* sedan = new Sedan("BMW", "535d", 2012 + i, licencePlates[i], false);
administration->Add(sedan);
}
for (int i = 4; i < 6; i++)
{
Car* limousine = new Limousine("Rolls Roys", "Phantom Extended Wheelbase", 2015, licencePlates[i], true);
administration->Add(limousine);
}
}
int main( void )
{
RentalAdministration administration;
addTestDataToAdministration(&administration);
}
So the compiler tells me that the variable: "RentalAdministration administration" does not exist.
So if we have look in my rentaladministration header. We see this:
#ifndef RENTALADMINISTRATION_H
#define RENTALADMINISTRATION_H
#include <vector>
#include "car.h"
class RentalAdministration
{
private:
std::vector<Car*> Cars;
Car* FindCar(std::string licencePlate);
Car* FindCarWithException(std::string licencePlate);
public:
std::vector<Car*> GetCars() const {return Cars;}
bool Add(Car* car);
bool RentCar(std::string licencePlate);
double ReturnCar(std::string licencePlate, int kilometers);
void CleanCar(std::string licencePlate);
RentalAdministration();
~RentalAdministration();
};
#endif
This is the exact error:
src/main.cpp:18:34: error: variable or field ‘addTestDataToAdministration’ declared void
void addTestDataToAdministration(RentalAdministration* administration)
^
src/main.cpp:18:34: error: ‘RentalAdministration’ was not declared in this scope
src/main.cpp:18:56: error: ‘administration’ was not declared in this scope
void addTestDataToAdministration(RentalAdministration* administration)
Help will be appreciated!
Edit:
I am getting warnings in sublime for the Sedan and Limousine headers. Something that has to do with some static constants. I think it was called a GNU extension. Maybe it has something to do with it.
Even when I comment the call of that function out. I get the same error.
I am calling that function nowhere else.
Some people say that the cause might be in these headers:
#ifndef LIMOUSINE_H
#define LIMOUSINE_H
#include "Car.h"
//c
class Limousine : public Car
{
private:
bool needsCleaning;
bool hasMiniBar;
static const double priceperkm = 2.5;
public:
double Return(int kilometers);
void Clean();
bool GetHasMiniBar() const { return hasMiniBar;}
void SetHasMiniBar(bool value) {hasMiniBar = value;}
Limousine(std::string manufacturer, std::string model, int buildYear, std::string licencePlate, bool hasminiBar);
~Limousine();
};
#endif
2:
#ifndef SEDAN_H
#define SEDAN_H
#include "Car.h"
//c
class Sedan : public Car
{
private:
int lastCleanedAtKm;
bool hasTowBar;
bool needsCleaning;
static const double priceperKm = 0.29;
public:
void Clean();
int GetLastCleanedAtKm() const {return lastCleanedAtKm;}
void SetLastCleanedAtKm(bool value){ lastCleanedAtKm = value;}
bool GetHasTowBar() const {return hasTowBar;}
void SetHasTowBar(bool value) {hasTowBar = value;}
bool GetNeedsCleaning() const {return needsCleaning;}
void SetNeedsCleaning(bool value){needsCleaning = value;}
Sedan(std::string manufacturer, std::string model, int buildYear, std::string licencePlate, bool hastowBar);
~Sedan();
};
#endif
class Limousine : public Car
{
private:
static const double priceperkm = 2.5;
...
}
Remove the static and declare the member simply as const double, example:
class Limousine : public Car
{
private:
const double priceperkm = 2.5;
...
}
The error message ‘RentalAdministration’ was not declared in this scope indicates that the right header file for RentalAdministration was not included. Check the file names to make sure class declaration for RentalAdministration is in the right file.
Restarting the terminal has somehow solved this error. I got another error this time, which I solved already. I missed the destructor. It stood in the header file, but not in the cpp file.
Buggy terminals...
Basically for some reason new object is wrong type. All source code is on github https://github.com/teuro/sfml-radar. If it's help please fork at will.
I have following class:
#ifndef _VIEW_HPP
#define _VIEW_HPP
#include <iostream>
#include "sfml_drawsurface.hpp"
class View {
protected:
View(Drawsurface& d) : drawer(d) {
std::clog << "View::View()" << std::endl;
}
Drawsurface& drawer;
virtual void draw() = 0;
};
#endif
That is base class for all different kind of views. Now I have derived sub-class
#ifndef _GAME_VIEW_HPP
#define _GAME_VIEW_HPP
#include <vector>
#include <iostream>
#include <typeinfo>
#include "view.hpp"
#include "../models/game.hpp"
class Gameview : public View {
public:
Gameview(Drawsurface& d);
~Gameview();
void draw();
private:
Drawsurface& drawer;
};
#endif // _GAME_VIEW_HPP
Then abstract class Drawsurface
/**
* drawsurface base for all graphics pure abstract
* provide only interface quite high-level
* 2014/06/02
* Juha Teurokoski
**/
#ifndef _DRAWSURFACE_HPP
#define _DRAWSURFACE_HPP
#include <string>
#include "../models/point.hpp"
class Drawsurface {
public:
bool font_loaded;
virtual void rectangleColor(Point& a, Point& b, unsigned int color) = 0;
virtual void lineColor(Point& a, Point& b, unsigned int color) = 0;
virtual void circleColor(Point& a, unsigned int rad, unsigned int color) = 0;
virtual void trigonColor(Point& a, Point& b, Point& c, unsigned int color) = 0;
virtual void trigonColor(Point& a, unsigned int size, unsigned int color) = 0;
virtual void load_font(std::string font) = 0;
virtual void draw_picture(std::string tiedosto, Point& a, bool center = false) = 0;
virtual void draw_text(std::string text, Point& a, unsigned int color = 0) = 0;
virtual int get_fontsize() = 0;
virtual void flip() = 0;
virtual void clear_screen() = 0;
virtual ~Drawsurface() { }
};
#endif
Now if I create new instance of sfml_drawsurface which is sub-class of Drawsurface. For some reason new object is Drawsuface istead of sfml_drawsurface. Below is sfml_drawsurface class.
#ifndef SFML_DRAWSURFACE_HPP
#define SFML_DRAWSURFACE_HPP
/**
* sfml-drawsurface provides basic drawing, pictures and text
* require drawsurface
* 2014/06/02
* Juha Teurokoski
**/
#include "drawsurface.hpp"
#include <vector>
#include <stdexcept>
#include <iostream>
#include <SFML/Graphics.hpp>
class sfml_drawsurface : public Drawsurface {
public:
sfml_drawsurface(sf::RenderWindow& window);
~sfml_drawsurface();
void rectangleColor(Point& a, Point& b, unsigned int color);
void circleColor(Point& a, unsigned int rad, unsigned int color);
void lineColor(Point& a, Point& b, unsigned int color);
void trigonColor(Point& a, Point& b, Point& c, unsigned int color);
void trigonColor(Point& a, unsigned int _size, unsigned int color);
void draw_picture(std::string tiedosto, Point& a, bool center = false);
void draw_text(std::string text, Point& a, unsigned int color);
void load_font(std::string font);
void clear_screen();
int get_fontsize();
void flip();
protected:
private:
sf::RenderWindow& window;
sf::Font font;
sf::Color active;
sf::Color normal;
};
#endif // SFML_DRAWSURFACE_HPP
I create new object like this:
sfml_drawsurface drawer(window);
this->gameview = new Gameview(drawer);
std::clog << typeid(drawer).name() << std::endl;
And everything seems to be right, because std::clog outout is '16sfml_drawsurface'.
Next place is draw-method then happens something really weird.
Same print is now '11Drawsurface'.
Looks like Mike had the right idea. From your Program.cpp file you have in your constructor:
Program::Program() {
Game game;
...
this->gamecontroller = new Gamecontroller(game); //Probably also bad
sfml_drawsurface drawer(window);
this->gameview = new Gameview(drawer);
}
The problem is that drawer ceases to exist once the constructor is finished leaving you with a dangling reference and undefined behaviour. Looks like you may have the same problem with the game variable.
Solution is to not have them as local variables but as either class members (preferred) or dynamically allocated (it depends how long you need to have them around).
I get this error
invalid conversion from 'GameObject*' to 'std::vector::value_type {aka SDLGameObject*}' [-fpermissive]
This is my code I don't know what is wrong because in my class MainMenu it works this is my class Playstate.cpp
bool PlayState::onEnter()
{
SDL_ShowCursor(1);
//parse the state
TheTextureManager::Instance()->load("assets/button.png", "test", TheGame::Instance()->getRenderer());
GameObject* pGameObject1 = TheGameObjectFactory::Instance()->create("MenuButton");
pGameObject1->load(new LoaderParams(120, 300, 400, 100, "test", 4, 4, 4));
m_gameObjects.push_back(pGameObject1);
}
GameObject.h
#include "LoaderParams.h"
#include <string>
using namespace std;
class GameObject {
public:
virtual void draw() = 0;
virtual void update() = 0;
virtual void clean() = 0;
virtual void load(const LoaderParams* pParams)=0;
protected:
GameObject() {}
virtual ~GameObject() {}
};
#endif /* GAMEOBJECT_H_ */
SDLGameObject.h
#ifndef SDLGAMEOBJECT_H_
#define SDLGAMEOBJECT_H_
#pragma once
#include "GameObject.h"
#include "LoaderParams.h"
#include "TextureManager.h"
#include "Vector2D.h"
class SDLGameObject : public GameObject {
public:
SDLGameObject();
virtual void draw();
virtual void update();
virtual void clean(){}
virtual void load(const LoaderParams* pParams);
Vector2D& getPosition() { return m_position; }
virtual int getWidth() { return m_width; }
virtual int getHeight() { return m_height; }
protected:
Vector2D m_position;
Vector2D m_velocity;
Vector2D m_acceleration;
int m_width;
int m_height;
int m_currentRow;
int m_currentFrame;
std::string m_textureID;
};
#endif /* SDLGAMEOBJECT_H_ */
MainMenuState.cpp here it does work!!
bool MainMenuState::onEnter()
{
SDL_ShowCursor(1);
//parse the state
TheTextureManager::Instance()->load("assets/button.png", "playbutton" , TheGame::Instance()->getRenderer());
TheTextureManager::Instance()->load("assets/exit.png", "exitbutton" , TheGame::Instance()->getRenderer());
GameObject* pGameObject = TheGameObjectFactory::Instance()->create("MenuButton");
GameObject* pGameObject1 = TheGameObjectFactory::Instance()->create("MenuButton");
pGameObject->load(new LoaderParams(120, 150, 400, 100, "playbutton", 0, 1, 2));
pGameObject1->load(new LoaderParams(120, 300, 400, 100, "exitbutton", 1, 2, 2));
m_gameObjects.push_back(pGameObject);
m_gameObjects.push_back(pGameObject1);
m_callbacks.push_back(0);
m_callbacks.push_back(s_menuToPlay);
m_callbacks.push_back(s_exitFromMenu);
//set callbacks for menu items
setCallbacks(m_callbacks);
std::cout << "Entering MainMenuState\n";
return true;
}
SDLGameObject derives from the base class GameObject. Your vector m_gameObjects stores pointers to SDLGameObject, but you are giving it a pointer to a GameObject.
This conversion is not possible as a GameObject is not necessarily an SDLGameObject.
If you are sure that this is the case you can do this:
SDLGameObject* p = dynamic_cast<SDLGameObject>(pGameObject1);
if(!p) {
// pGameObject1 is actually not an SDLGameObject
}
m_gameObjects.push_back(p);
Or change the definition of m_gameObjects to store pointers to GameObject.
My question is very beginner, and yes I have looked it up extensively, but when I do the things I've found online Xcode gives me errors.
Basically, I'm just curious how to implement a constructor for a derived class. My class is called "Sensor" and the derived classes are digitalSensor and analogSensor.
Here's my sensor.h:
#ifndef __Program_6__sensor__
#define __Program_6__sensor__
#include <iostream>
class sensor {
char* SensorName;
float energyDraw;
int functioning;
int onoff;
public:
sensor(char*n, float pc);
virtual void print();
void setOK(int K);
int getOK();
void setOnOff(int n);
int getOnOff();
};
//---------
class digitalSensor : public sensor {
int reading;
public:
digitalSensor(char*n, float pc);
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};
class analogSensor : public sensor {
int Reading;
int minRead;
int maxRead;
public:
analogSensor(char *n, float pc, int mm, int mx);
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};
#endif /* defined(__Program_6__sensor__) */
And here's my sensor.cpp, you can see the beginnings of my digitalSensor work at the bottom.
#include "sensor.h"
#include "definitions.h"
using namespace std;
//--------SENSOR CLASS------------//
sensor::sensor(char *n, float pc) {
SensorName = (char*)malloc(strlen(n)+1);
energyDraw = pc;
functioning = WORKING;
onoff = OFF;
}
void sensor::print() {
cout << " Sensor: " << SensorName;
cout << " Power Consumption: " << energyDraw;
if (functioning == WORKING) {
cout << "\nSensor is functioning correctly\n";
if (onoff == ON) {
cout << "Sensor is On";
}
if (onoff == OFF) {
cout << "Sensor is Off";
}
}
if (functioning == NOTWORKING) {
cout << "Sensor is not functioning correctly";
}
}
void sensor::setOK(int k) {
functioning = k;
}
int sensor::getOK() {
return functioning;
}
void sensor::setOnOff(int n) {
onoff = n;
}
int sensor::getOnOff() {
return onoff;
}
//---------------------------------//
//*********DIGITAL SENSOR**********//
sensor digitalSensor::digitalSensor(char *n, float pc) {
}
In a nutshell: I need to make a constructor function for the digital sensor class. What am I missing, how do I do that? Thanks in advance for any help or knowledge on this!
Implement its constructor like this:
digitalSensor::digitalSensor(char*n, float pc) : sensor(n, pc)
{
}
As you can see, it doesn't return anything and it calls its parent's constructor.
But you're doing this which is wrong:
sensor digitalSensor::digitalSensor(char *n, float pc) {
^^^^^^ constructors shall not return anything
}
You should call your base class constructor at the derived class's member initialization list.
For example:
class digitalSensor : public sensor {
int reading;
public:
digitalSensor(char*n, float pc): sensor(n, pc), reading(0){}
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};
This defines the digitalSensor constructor inline. You can also define it with scope resolution operator outside class:
digitalSensor::digitalSensor(char*n, float pc):sensor(n, pc), reading(0){}
//^^Note that constructor of a class does not have any return type
It really depends on how your base class constructors are provided. But this could be one way to do it. You may find Initializing base classes and members useful.
I have a little problem, i probably included the class files wrongly, since i can't acces members of the enemy class. What am i doing wrong?
my cpp for class
#include "classes.h"
class Enemy
{
bool alive;
double posX,posY;
int enemyNum;
int animframe;
public:
Enemy(int col,int row)
{
animframe = rand() % 2;
posX = col*50;
posY = row*50;
}
Enemy()
{
}
void destroy()
{
alive = 0;
}
void setposX(double x)
{x = posX;}
void setposY(double y)
{y = posY;}
};
my header for class:
class Enemy;
my main:
#include "classes.h"
Enemy alien;
int main()
{
alien. // this is where intelisense tells me there are no members
}
Your main file will only see what you wrote in the header, which is that Enemy is a class. Normally, you'd declare your whole class with fields and method signatures in the header files, and provide implementations in the .cpp file.
classes.h:
#ifndef _CLASSES_H_
#define _CLASSES_H_
class Enemy
{
bool alive;
double posX,posY;
int enemyNum;
int animframe;
public:
Enemy(int col,int row);
Enemy();
void destroy();
void setposX(double x);
void setposY(double y);
};
#endif
classes.cpp:
#include "classes.h"
//....
void Enemy::destroy(){
//....
}
//....
In addition to Vlad's answer, your file with main doesn't know anything about the Enemy class, other than that it exists.
In general, the class declarations goes in the header file, and the function definitions go in another.
Consider splitting the files like:
classes.h:
#ifndef CLASSES_H
#define CLASSES_H
class Enemy
{
private:
bool alive;
double posX,posY;
int enemyNum;
int animframe;
public:
Enemy(int col,int row);
Enemy();
void destroy();
void setposX(double x);
void setposY(double y);
};
#endif//CLASSES_H
Note the "include guards" which prevent the same file from being included more than once. Good practice to use on header files, or else you get annoying compilation errors.
classes.cpp:
#include "classes.h"
Enemy::Enemy(int col,int row)
{
animframe = rand() % 2;
posX = col*50;
posY = row*50;
}
Enemy::Enemy()
{
}
void Enemy::destroy()
{
alive = 0;
}
void Enemy::setposX(double x) {x = posX;}
void Enemy::setposY(double y) {y = posY;}