I have consulted many websites but have not successfully completed my code.
I am trying to write some code that spits out information about a car, once the user provides information. After compiling, the compiler says that "declaration does not declare anything." Here's the code:
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car()
{
}
void Car::accel()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}
void Car::setSpeed(int newSpeed)
{
speed = newSpeed;
}
int Car::getSpeed()
{
return speed;
}
void Car::setMake(string newMake)
{
make = newMake;
}
string Car::getMake()
{
return make;
}
void Car::setYearModel(int newYearModel)
{
yearModel = newYearModel;
}
int Car::getYearModel()
{
return yearModel;
}
int main()
{
Car auto; //instance of class Car
int autoYear; //year of auto
string autoMake; //make of auto
int autoSpeed; //speed of auto
cout << "Enter the year model of your car. ";
cin >> autoYear;
cout << "Enter the make of your car. ";
cin >> autoMake;
auto.setYear(autoYear); //stores input year
auto.setMake(autoMake); //stores input make
}
And the header, Car.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H
#define CAR_H
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car();
void accel();
void brake();
void setSpeed(int newSpeed);
int getSpeed();
void setMake(string newMake);
string getMake();
void setYearModel(int newYearModel);
int getYearModel();
};
#endif
I also have errors for missing semicolons every time my object auto appears ("expected ; before auto" and "expected primary-expression before auto"). What could be the problem?
auto is a keyword. You'll need to pick a different name.
Related
#include <iostream>
#include <string>
#ifndef FOOD_H
#define FOOD_H
using namespace std;
this class for insertion sorting for food's price or food's calorie
class Food
{
private:
string Name;
float Calorie;
float Price;
public:
void setName(string n);
void setCalorie(float c);
void setPrice(float p);
string getName();
float getCalorie();
float getPrice();
Food();
Food(string n,float c,float p);
void Print(Food FoodArray[],int);
void Sort(Food FoodArray[], float);
void Sort2(Food FoodArray[], float);
};
#endif
#include <iostream>
#include <string>
#include "Food.h"
#ifndef IMPLEMENTER_CPP
#define IMPLEMENTER_CPP
using namespace std;
void Food::setName(string n){Name=n;}
void Food::setPrice(float p){Price=p;}
void Food::setCalorie(float c){Calorie=c;}
string Food::getName(){return Name;}
float Food::getPrice(){ return Price;}
float Food::getCalorie(){ return Calorie;}
Food::Food(string n,float c,float p)
{
Food::Name=n;
Food::Calorie=c;
Food::Price=p;
}
Food::Food()
{
Food::Name="";
Food::Calorie=0.00;
Food::Price=0.00;
}
void Food::Print(Food FoodArray[],int num)
{
for (int i=0;i>num;i++)
{
cout<<"-------------------------------------------------"<<endl;
cout<<"NAME: "<<FoodArray[i].getName()<<" CALORIE: "<<FoodArray[i].getCalorie()<<" PRICE: "<<FoodArray[i].getPrice()<<endl;
cout<<"-------------------------------------------------"<<endl;
}
}
void Food::Sort(Food FoodArray[], float pri)
{
int i,j;
float tmp;
string t;
for(i=1;i<=pri-1;i++)
{
tmp=FoodArray[i].getPrice();
t=FoodArray[i].getName();
j=i-1;
while((tmp<FoodArray[j].getPrice())&&(j>=0))
{
FoodArray[j+1]=FoodArray[j];
j--;
}
FoodArray[j+1].setName(t);
FoodArray[j+1].setPrice(tmp);
}
cout<<endl<<"Sorted list is shown below: "<<endl;
}
void Food::Sort2(Food FoodArray[], float cal)
{
int i, j;
float tmp;
string t;
for(i=1;i<=cal-1;i++)
{
tmp=FoodArray[i].getCalorie();
t=FoodArray[i].getName();
j=i-1;
while((tmp<FoodArray[j].getCalorie())&&(j>=0))
{
FoodArray[j+1]=FoodArray[j];
j=j-1;
}
FoodArray[j+1].setCalorie(tmp);
FoodArray[j+1].setName(t);
}
cout<<endl<<"Sorted list is shown below: "<<endl;
}
#endif
#include <iostream>
#include <string>
#include "Food.h"
#include "Implementer.cpp"
using namespace std;
contains the main method. From this class an array of food will be created and the sorting function
will be called to sort the array.
class client
{
public:
Food *foodArray[];
void info()
{int num;
string name,answer;
float calorie,price;
loop2:
cout<<"how many do you want ? ";
cin>>num;
if (num>0)
{
for (int i=0; i<num; i++)
{
cout<<i+1<<"- ";
cout<<"Enter Food name: ";
cin>>name;
cout<<"Enter Calories: ";
cin>>calorie;
cout<<"Enter Price: ";
cin>>price;
Food food=Food(name,calorie,price);
*foodArray[i]=food;
}
foodArray[num]->Print(*foodArray,num);
loop:
cout<<"Would you like to sort the foods based on Price or Calories? P/C"<<endl;
cin>>answer;
if (answer=="P")
{
foodArray[num]->Sort(*foodArray,price);
foodArray[num]->Print(*foodArray,num);
}
else if (answer=="C")
{
foodArray[num]->Sort2(*foodArray,calorie);
foodArray[num]->Print(*foodArray,num);
}
else
{
cout<<"please choose P or C."<<endl;
goto loop;
}
}
else
{
goto loop2;
}
}
};
int main()
{
client C;
C.info();
return 0;
}
I'm working on a multiple inheritance exercise and I'm running into a strange error. My code is not returning the correct information to the console. It is just outputting zero, I have checked multiple times in my code and I can't seem to find anything obviously wrong. I'm fairly new to C++ so any help I would appreciate it, in addition to any other critique.
The console will output
Maverick
South station
50 - passengers, is ok
40 - speed
0 - it is supposed to take distance/mph and output 2.6 in this case, but is returning nothing.
MBTA.cpp
#include "MBTA.h"
//objects
transportation Dest;
MBTA::MBTA()
{
}
MBTA::MBTA(string strIn, string strInTransport, int iIn, int distIn, int eIn)
{
setTrain(strIn);
//Destination
Dest.setTransport(strInTransport);
//set passengers
setPass(iIn);
Dest.setMilesToDest(distIn);
engine.setMPH(eIn);
//outputs train information
printTrainDestinationHours();
//used printf as I was running into issue with using cout here
//cout << " I am going to ";
printf("I am going to %s\n", Dest.getTransport().c_str());
//uses engine stats function
cout << "I go " << engine.getMPH() << endl;
printf("It will take me %.2f hours to arrive", redline.getTotal());
}
void MBTA::setTravelDist(int iIn)
{
double destdistance = Dest.getDist();
double trainMPH = engine.getMPH();
//this divides miles by MPH, this might return a float
redline.setTotal(50, 10);
}
MBTA::~MBTA()
{
}
MBTA.H
#pragma once
#include "train.h"
class MBTA :
public train
{
public:
engine engine;
train redline;
MBTA();
//train, destination, passengers, traveldist, speed
MBTA(string, string, int, int, int);
void setTravelDist(int);
//double getTotal();
//uses engine stats function
//double total = 0;
~MBTA();
};
Train.cpp
#include "train.h"
#include <iostream>
#include <cstdio>
#include <cmath>
using std::string;
using std::cout;
using std::endl;
//object member for transport
transportation tTrain;
train::train()
{
}
void train::printTrainDestinationHours()
{
printf("\n\nTrain type: %s\n", getTrain().c_str());
//passengers
printf("I have %d passengers\n", getPass());
}
void train::setPass(int iIn)
{
passengers = iIn;
}
int train::getPass()
{
return passengers;
}
void train::setTrain(string strIn)
{
trainName = strIn;
}
string train::getTrain()
{
return trainName;
}
void train::setTotal(int aIn, int bIn)
{
//dist / mph
total = aIn / bIn;
}
double train::getTotal()
{
return total;
}
train::~train()
{
}
Train Header
#pragma once
#include <iostream>
#include <cstdio>
using std::string;
using std::cout;
using std::endl;
#include "engine.h"
#include "transportation.h"
class train : public transportation
{
public:
train();
void printTrainDestinationHours();
//set and get destination
//num of pass
void setPass(int);
int getPass();
//train
void setTrain(string);
string getTrain();
//distance
void setTotal(int, int);
double getTotal();
~train();
private:
engine engineStats;
int total = 0;
string trainName = "";
string destination = "";
int passengers = 0;
};
engine.cpp
#include "engine.h"
engine::engine()
{
}
void engine::setMPH(int iIn)
{
MPH = iIn;
}
int engine::getMPH()
{
return MPH;
}
engine::~engine()
{
}
engine header
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
'''
transportation cpp
'''
#pragma once
class engine
{
public:
engine();
//return
void setMPH(int);
int getMPH();
~engine();
protected:
int MPH = 0;
};
transportation header
#include "transportation.h"
transportation::transportation()
{
}
void transportation::setTransport(string strIn)
{
destination = strIn;
}
string transportation::getTransport()
{
return destination;
}
void transportation::setMilesToDest(int iIn)
{
MilesToDestination = iIn;
}
int transportation::getDist()
{
return MilesToDestination;
}
transportation::~transportation()
{
}
main file
#include <iostream>
using std::string;
using std::cout;
using std::endl;
using std::cin; //for ignore
#include "challenger.h"
#include "MBTA.h"
#include "plane.h"
int main()
{
//object composition of vehicle type
// vehicle type location, passengers, MPH , distance
challenger SRT8707("Boston", 2, 100, 200);
plane boeing("boeing", "houston", 50, 500, 300);
MBTA redline("Maverick", "South station", 50, 100, 40);
//pause and blank line
cout << endl << endl;
cin.ignore();
}
I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.
I keep getting various errors in my code can someone please run it through their compiler and help me resolve them?? I fixed a few and the one I am getting now is no matching function for call to 'classRooms::ClassRooms(std::string&, int&, .....
//classRoom.h
#ifndef CLASSROOMS_H
#define CLASSROOMS_H
#include <iostream>
#include <string>
#include "ClassRooms.h"
using namespace std;
class ClassRooms
{
public:
ClassRooms(int nRooms=100)
: numRooms(0), rooms(new ClassRooms[nRooms]) { }
~ClassRooms()
{
delete [] rooms;
}
void addRoom(const ClassRooms& cr)
{
rooms[numRooms++] = cr;
}
string findRoom(int seats)const;
int getSeats();
double getAreaPerSeat();
string getRoomNumber();
private:
int numRooms;
ClassRooms *rooms;
int numSeats;
double length, width;
};
#endif //CLASSROOMS_H
//ClassRooms.h
#ifndef CLASSROOMS_H
#define CLASSROOMS_H
#include <iostream>
#include <string>
#include "classRoom.h"
using namespace std;
class ClassRooms
{
public:
ClassRooms(int nRooms=100)
: numRooms(0), rooms(new ClassRooms[nRooms]) { }
~ClassRooms()
{
delete [] rooms;
}
void addRoom(const ClassRooms& cr)
{
rooms[numRooms++] = cr;
}
string findRoom(int seats)const;
private:
int numRooms;
ClassRooms *rooms;
};
#endif //CLASSROOMS_H
//main.cpp
#include <iostream>
#include <fstream>
#include "ClassRooms.h"
using namespace std;
int main()
{
ifstream fin("rooms.txt");
if (!fin)
{
cout << "Cannot open file\n";
return 1;
}
string roomNum;
int seats;
double len, wid;
ClassRooms classRooms;
while (fin >> roomNum >> seats >> len >> wid)
classRooms.addRoom(ClassRooms(roomNum, seats, len, wid));
fin.close();
while (seats > 0)
{
cout << "Enter MAX capacity: ";
cin >> seats;
cout << "Your best room is " << classRooms.findRoom(seats) << endl;
}
}
//ClassRooms.cpp
#include "classRoom.h"
string ClassRooms::findRoom(int seats)const
{
int maxIndex = 0;
while (maxIndex < numRooms && rooms[maxIndex].getSeats() < seats)
++maxIndex;
if (maxIndex == numRooms) return "";
for (int i = 0; i < numRooms; ++i)
if (rooms[i].getSeats() >= seats
&& rooms[i].getAreaPerSeat() > rooms[maxIndex].getAreaPerSeat())
maxIndex = i;
return rooms[maxIndex].getRoomNumber();
}
You have no Classrooms constructor that takes a (string, int, double, double), so therefore, this ClassRooms(roomNum, seats, len, wid) is an error. You can easily add an appropriate constructor to Classrooms though.
ClassRooms(string roomNum, int seats, double len, double wid){
//do something
}
Same code that I was working on last night, has thrown up a whole new error. One that I've never encountered before, and I am at the point of considering throwing things at my PC. But, everyone here was very helpful last night, so I thought I'd see if anyone had any ideas on this new problem.
Something is causing "Microsoft C++ exception: std::bad_alloc" and I think it's within the first line of the main.cpp, but as that is just creating the player as a Hero (child of creature) class. I can't see why it can't do it.
I know it's probably something stupid, that I've done badly ... but any help would be appreciated!
//main.cpp
#include "Creature.h"
#include "Hero.h"
#include "Monster.h"
#include <conio.h>
using namespace std;
int main()
{
Hero player(1);
Monster baddie;
player.setX(1);
player.setY(1);
baddie.setX(20);
baddie.setY(20);
player.Display();
baddie.Display();
baddie.chase(player);
player.Display();
baddie.Display();
_getch();
return 0;
}
===================================
//Creature.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Creature
{
protected:
int m_xpos;
int m_ypos;
string m_name;
public:
Creature(string name, int xpos, int ypos);
void Display(void);
void left(void);
void right(void);
void up (void);
void down(void);
void setX(int x);
void setY(int y);
int getX(void);
int getY(void);
};
===================================
//monster.h
#pragma once
#include "Creature.h"
class Monster : public Creature
{
public:
Monster();
void chase(class Hero);
bool eaten(class Hero);
};
===================================
//Hero.h
#pragma once
#include "Creature.h"
class Hero : public Creature
{
private:
int m_lives;
int m_score;
public:
Hero(int lives);
void Display(void);
void setScore(void);
};
===================================
//creature.cpp
#include "Creature.h"
Creature::Creature(string name, int xpos, int ypos)
{
m_xpos = xpos;
m_ypos = ypos;
m_name = name;
}
void Creature::Display(void)
{
cout << m_name << endl;
cout << m_xpos << endl;
cout << m_ypos << endl;
}
void Creature::left(void)
{
m_xpos = m_xpos+1;
}
void Creature::right(void)
{
m_xpos = m_xpos-1;
}
void Creature::up(void)
{
m_ypos = m_ypos-1;
}
void Creature::down(void)
{
m_ypos = m_ypos+1;
}
void Creature::setX(int x)
{
m_xpos = x;
}
void Creature::setY(int y)
{
m_ypos = y;
}
int Creature::getX(void)
{
return m_xpos;
}
int Creature::getY(void)
{
return m_ypos;
}
===================================
//Hero.cpp
#include "Creature.h"
#include "Hero.h"
Hero::Hero(int lives) : Creature(m_name, m_xpos, m_ypos)
{
m_lives = lives;
}
void Hero::Display(void)
{
Creature::Display();
cout << "Lives: " << m_lives << endl;
cout << "Score: " << m_score << endl;
}
void Hero::setScore(void)
{
m_score = 0;
}
===================================
//Monster.cpp
#include "Creature.h"
#include "Monster.h"
#include "Hero.h"
Monster::Monster() : Creature(m_name, m_xpos, m_ypos)
{
}
void Monster::chase(Hero hero)
{
if(getX() < hero.getX())
{
right();
}
if(getX() > hero.getX())
{
left();
}
if(getX() < hero.getX())
{
down();
}
if(getX() >hero.getX())
{
up();
}
}
bool Monster::eaten(Hero hero)
{
if((getX() == hero.getX())&&(getX() == hero.getX()))
{
return true;
}
}
===================================
The problem lay in Hero::Hero(int lives) : Creature(m_name, m_xpos, m_ypos) and the equivilant with the Monster.cpp file.
Changing them to Hero::Hero(int lives) : Creature("", 0,0) fixed the memory problem.
Thanks again to a wonderful community!
Hopefully, you'll never see this code again! (fingers crossed!)
The error is with this line:
Hero::Hero(int lives) : Creature(m_name, m_xpos, m_ypos)
You cannot create the Creature sub-object by passing its own uninitialized data members to it. You need to pass some sort of valid values to the base-class constructor, like Creature("", 0, 0) for example.
The error is caused, somehow, by the attempt to copy an uninitialized std::string object.