What is wrong with my code? My program will not compile - c++

Ok, so my assignment is to build on an existing code from the book. I have to add the 3rd box and then calculate the total for all 3 boxes. Here is what I've written so far, but it will not compile. Please help me find the problem. Thanks.
The program I'm using is MS Visual C++ and the complile error I get is
error C2447: '{' : missing function header (old-style formal list?)
referring to the { after my int Total_Volume line
// Structures_and_classes.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
class CBox // Class definition at global scope
{
public:
double m_Length; // Length of a box in inches
double m_Width; // Width of a box in inches
double m_Height; // Height of a box in inches
};
int main();
int Total_Volume;
{
CBox box1;
CBox box2;
CBox box3;
double boxVolume = 0.0; // Stores the volume of a box
box1.m_Height = 18.0; // Define the values
box1.m_Length = 78.0; // of the members of
box1.m_Width = 24.0; // the object box1
box2.m_Height = box1.m_Height - 10; // Define box2 Box 2 H = 8
box2.m_Length = box1.m_Length/2.0; // members in Box 2 L = 39
box2.m_Width = 0.25*box1.m_Length; // terms of box1 Box 2 W = 6
box3.m_Height = box1.m_Height + 2; // Define box3 Box 3 H = 20
box3.m_Length = box1.m_Length - 18; //members in Box 3 L = 50
box3.m_Width = box1.m_Width + 1; //terms of box1 Box 3 W = 25
// Box1
boxVolume = box1.m_Height*box1.m_Length*box1.m_Width;cout << endl;
<< "Volume of box1 = " << boxVolume;
cout << endl;
// Box 2
boxVolume = box2.m_Height*box2.m_Length*box2.m_Width;cout << endl;
<< "Volume of box2 = " << boxVolume;
cout << endl;
// Box 3
boxVolume = box3.m_Height*box3.m_Length*box3.m_Width;cout << endl;
<< "Volume of box3 = " << boxVolume;
cout << endl;
//Calculate Total Volume
Total_Volume = (box1.m_Height*box1.m_Length*box1.m_Width)+
(box2.m_Height*box2.m_Length*box2.m_Width)+
(box3.m_Height*box3.m_Length*box3.m_Width);
return 0;
}

Change:
int main();
int Total_Volume;
{
to:
int main()
{
int Total_Volume;
That will fix your immediate problem, although I suspect you'll have a few more questions today :-)
The actual problem with your current code is that it defines a prototype for main, followed by a file-level variable, followed by a naked brace, which is why it's complaining about a missing function header.
You may also want to consider changing your main function to one of:
int main (int argc, char *argv[])
int main (void)
(probably the second in your case) as these are the two forms required to be supported by the ISO C standard. Implementations are free to accept others if they wish but I usually prefer my code to be as standard as possible. The reason I say "may" is because it's not necessarily required to get your code working, more of a style thing.

int main();
int Total_Volume;
{
should be
int main()
{
int Total_Volume;

It looks like you mixed up a couple lines:
int main();
int Total_Volume;
{
CBox box1;
CBox box2;
CBox box3;
looks like it should be:
int main() {
int Total_Volume;
CBox box1;
CBox box2;
CBox box3;

Try moving
int Total_Volume;
after the {

Goodness me. Please check the preview and at least make sure your question looks like prose plus some code. Edit okay, let's assume that was a glitch that's been sorted out. The rest of my answer still holds.
A little bit of digging suggests the first problem is that you don't have a properly defined main() function. This is the first thing one learns about C++ typically, so in the first instance get that right.
Good luck.

You probably intended to write:
int main()
{
int TotalVolume;
You can't start a block where you did.
You have declared that there will be a function main(), and that there's a global variable TotalVolume, but the anonymous block following these is not allowed.

Related

Pointers with cout in C++

I am in the process of learning C++ and SDL, and when I tried to print the content of an array I ran into some confusion. I have an array with two values in it, 2 and 3. When I want to print the values like this:
int* test = myApp.countDivisions(5);
std::cout << "Horizontal: " << *test<< std::endl;
std::cout << "Vertical: " << *(test+1) << std::endl;
I get:
Horizontal: -858993460
Vertical: -858993460
But when I write:
int* test = countDivisions(5);
int foo = *(test);
int boo = *(test+1);
std::cout << "Horizontal: " << foo << std::endl;
std::cout << "Vertical: " << boo << std::endl;
I get:
Horizontal: 2
Vertical: 3
I am confused as to why this happens. If anyone could explain why this behaviour happens, it would be great! I am aware that I should not be using C arrays in C++, but I am still interested in understanding what is happenning here!.
Edit: I modified a typo in the first example.
Also I got asked what my countDivisions(int) function does so here is the entire code:
#include <iostream>
#include <SDL.h>
class SDLApplication {
private:
//This is the window of the application:
SDL_Window* AppWindow;
//This is the surface displayed by the window:
SDL_Surface* WindowSurface;
SDL_Renderer* Renderer;
//This is the name of the App:
std::string AppName;
//These are the dimensions of the window displaying the App
int WindowWidth;
int WindowHeight;
public:
SDLApplication(std::string name) {
AppWindow = NULL;
WindowSurface = NULL;
AppName = name;
WindowHeight = 0;
WindowWidth = 0;
Renderer = NULL;
}
int* countDivisions(int divisions) {
//This helper functions takes as input the number of divisions on the screen and returns an array that tells
//us how many horizontal and vertical divisions we have, assuming we divide linearly starting from the right corner.
int horizontal = 0;
int vertical = 0;
int i = 0;
int divTemp = pow(2,i);
int divCount = divTemp;
int temp;
while (divCount < divisions) {
if (i % 2 == 0) {
//Our power of two is pair, so we are adding horizontal divisions
horizontal += divTemp;
}
else {
//Our power of two is odd, so we are adding vertical divisions
vertical += divTemp;
}
++i;
divTemp = pow(2,i);
temp = divCount + divTemp;
if ( temp> divisions) {
if (i % 2 == 0) {
//Our power of two is pair, so we are adding horizontal divisions
horizontal += divisions-divCount;
}
else {
//Our power of two is odd, so we are adding vertical divisions
vertical += divisions-divCount;
}
}
divCount =temp;
}
int result[] = { horizontal, vertical };
return result;
}
}
int main(int argc, char* argv[])
{
SDLApplication myApp("SDL_Test");
int* test = myApp.countDivisions(5);
std::cout << "Horizontal: " << *test << std::endl;
std::cout << "Vertical: " << *(test + 1) << std::endl;
return 0;
}
I think printing *int is undefined behaviour - it is kind of meaningless. This expression is a type. Its a bit like saying "where is human" rather then "where is the human called bob" (ok, bit of a rubbish analogy), a type does not have an address on its own.
Your second example int* test is a variable named test which has a type of int* (pointer to an integer). You set the value of the pointer test to something (whatever myApp.countDivisions(5); returns - you should tell us what that returns).
Then:
int foo = *(test);
int boo = *(test+1);
foo is an integer variable that you set to the value of what test points to - and not the address itself. boo is set to the contents of the next address (address of test + 1).
If you want to print the address of the pointers you should do:
std::cout << "Horizontal: " << test << std::endl;
If you want to print the value of what the pointer is pointing to you should do:
std::cout << "Horizontal: " << *test << std::endl;
This is called dereferencing. See this little example: https://godbolt.org/z/CzHbq6
update: updated as per question update
You are returning a pointer to a local variable called result. That variable is destroyed at the end of your countDevisions() function, which will lead to undefined behaviour (which you are seeing) meaning anything can happen!. See here for an example of that with the warnings printed out: https://godbolt.org/z/gW2XS4
"A" fix for that is to change the scope of result by making its lifetime the entire life of the program, this can be done by making it static. Note I do this for demonstration only - this is not a good solution, but see it here working: https://godbolt.org/z/goQJzx
Perhaps a better solution would be to return a container from the standard template library (STL) like std::vector (something like an array): https://godbolt.org/z/3DOyhq
Or perhaps (after reading your code properly) you don't really even want an array, it seems you just want two values: vertical and horizontal. So you could define your own struct and use that - this seems more optimal: https://godbolt.org/z/RmUM39. This also makes more sense to the user of your function by being able to reference horizontal/vertical by name and not by some array index.
TLDR: "turn on warnings" and search for "c++ return multiple values"
You need to include iostream and define three classes, and fix two additional typos.
#include <iostream>
typedef int SDL_Window;
typedef int SDL_Surface;
typedef int SDL_Renderer;
This results in code that gives a useful warning message, which tells you that SDLApplication::countDivisions returns the address of a local variable or temporary. As you later attempt to use that temporary object which has gone out of scope, the result is, not surprisingly, undefined behavior.
Your function returns multiple values. You could have created an std::tuple object, but I would just define a struct so you can return one value, with named members.
struct Divisions {
int horizontal;
int vertical;
};
class SDLApplication {
...
Divisions countDivisions(int divisions) {
...
return Divisions{ horizontal, vertical };
}
};
see also
Return multiple values to a method caller
Returning multiple values from a C++ function

(C++) multiplication wont give off expected results

hello :) so this is my first time writing a c++ program, im currently using code::blocks tho im pretty sure the issue ive got probably isnt related to the program at all but anyway...
i want to write a simple code, where two "boxes" are created and their volume is calculated and printed on the terminal. ive written this code on a single cpp file:
#include<iostream>
using namespace std;
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
l=length;
b=breadth;
h=height;
}
};
int main()
{
double volume = 0.0;
Box BoxA(2.0, 3.2, 6.0);
Box BoxB(2.5, 4.0, 5.0);
volume = BoxA.length * BoxA.breadth * BoxA.height;
cout << "Box a volume = " << volume <<endl;
volume = BoxB.length * BoxB.breadth * BoxB.height;
cout << "Box b volume = " << volume <<endl;
return 0;
}
so i build and run this thing, no errors but the results i get is this:
box a volume = -0
//and sometimes =0
box b volume = 0
but i dont understand what is wrong here. shouldnt the results be a=38.4 and b=50.0? what am i doing wrong here?
Your constructor assigns values to the passed arguments.
Try this instead:
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length=l;
breadth=b;
height=h;
}
};
As others have mentioned, there are other improvements that can be made regarding initializer lists and the use of using, and the study of programming in general and c++ in particular is an ongoing journey, never a destination, but this is the direct fix for the immediate problem.
The usual way to write constructors is with initializer lists:
Box(double l, double b, double h) : length(l), breadth(b), height(h)
{
}
This prevent exactly the same error that you had, exchanging the argument and member. If you tried to write : l(length), the compiler would have told you straight away that l is not a member of Box.
You don't even need separate names with initializer lists:
Box(double length, double breadth, double height)
: length(length), breadth(breadth), height(height)
{ }
This does initialize Box::height with the argument height.
#include<iostream>
class Box
{
public:
double length;
double breadth;
double height;
Box(double l, double b, double h)
{
length = l; // assign to the member variables, not parameters
breadth = b;
height = h;
}
};
int main(void)
{
double volume = 0.0;
Box BoxA(2.0, 3.2, 6.0);
Box BoxB(2.5, 4.0, 5.0);
volume = BoxA.length * BoxA.breadth * BoxA.height;
std::cout << "Box a volume = " << volume << std::endl;
volume = BoxB.length * BoxB.breadth * BoxB.height;
std::cout << "Box b volume = " << volume << std::endl;
return 0;
}
This is the refined version of your code. Note that you shouldn't use namespace std. That's a bad programming practice.

C++ Undeclared Identifier on Object creation

So I am new to c++, coming from C#. This is giving me several errors when compiling, which all seem to relate to this object declaration. Anyone able to show me the right way to do this?
I get an undeclared identifier where i declare tri(sideLength).
I have used this as a reference for object declaration, but it doesn't seem to be helping me.
Thanks.
#include <iostream> // Provides cout
#include <iomanip> // Provides setw function for setting output width
#include <cstdlib> // Provides EXIT_SUCCESS
#include <cassert> // Provides assert function
#include <stdexcept>
#include <math.h>
using namespace std; // Allows all standard library items to be used
void setup_cout_fractions(int fraction_digits)
// Precondition: fraction_digits is not negative.
// Postcondition: All double or float numbers printed to cout will now be
// rounded to the specified digits on the right of the decimal.
{
assert(fraction_digits > 0);
cout.precision(fraction_digits);
cout.setf(ios::fixed, ios::floatfield);
if (fraction_digits == 0)
cout.unsetf(ios::showpoint);
else
cout.setf(ios::showpoint);
}
int main()
{
const int MAX_SIDE_LENGTH = 6;
const int INITIAL_LENGTH = 1;
const int DIGITS = 4;
const int ARRAY_SIZE = 6;
// Set up the output for fractions and print the table headings.
setup_cout_fractions(DIGITS);
// Each iteration of the loop prints one line of the table.
for (int sideLength = 0; sideLength < MAX_SIDE_LENGTH; sideLength += 1)
{
EquilateralTriangle tri(sideLength);
//Square sq(sideLength);
//Pentagon_Reg pent(sideLength);
//Hexagon_Reg hex(sideLength);
//Heptagon_Reg hept(sideLength);
//Octagon_Reg octa(sideLength);
cout << "Type: " << tri.Name() << "has area: " << tri.Area() << " with SideLength = " << sideLength;
}
return EXIT_SUCCESS;
}
//Template
class GeometricFigure
{
public:
GeometricFigure() { }
double SideLength;
virtual double Area() { return 0; };
virtual char* Name() { return ""; };
};
class EquilateralTriangle : public GeometricFigure {
public:
EquilateralTriangle(double sideLength)
{
SideLength = sideLength;
}
char* Name() { return "Equilateral Triangle"; }
double Area() { return (sqrt(3) / 2 * pow(SideLength, 2)); }
};
In C++, the compiler reads your code from top-to-bottom, once. This is a holdover from when early C compilers only had a few kilobytes of memory to work with - C was designed so that a compiler would only need to look at a little bit of the code at a time.
Because of this, things must have been declared or defined as necessary, before you try to use them.
Move both classes somewhere before main. GeometricFigure must be before EquilateralTriangle, and EquilateralTriangle must be before main.
You would need to "declare" or tell the compiler, where to look for the EquilateralTriangle and GeometricFigure, "before" you use it first. you might want to take a look at the similar discussion at - C# declarations vs definitions

Should I be attempting to return an array, or is there a better solution?

A problem set for people learning C++ is
Write a short program to simulate a ball being dropped off of a tower. To start, the user should be asked for the initial height of the tower in meters. Assume normal gravity (9.8 m/s2), and that the ball has no initial velocity. Have the program output the height of the ball above the ground after 0, 1, 2, 3, 4, and 5 seconds. The ball should not go underneath the ground (height 0).
Before starting C++ I had a reasonable, but primarily self taught, knowledge of Java. So looking at the problem it seems like it ought to be split into
input class
output class
calculations class
Physical constants class (recommended by the question setter)
controller ('main') class
The input class would ask the user for a starting height, which would be passed to the controller. The controller would give this and a number of seconds (5) to the calculations class, which would create an array of results and return this to the controller. The controller would hand the array of results to the output class that would print them to the console.
I will put the actual code at the bottom, but it's possibly not needed.
You can probably already see the problem, attempting to return an array. I'm not asking how to get round that problem, there is a workaround here and here. I'm asking, is the problem a result of bad design? Should my program be structured differently, for performance, maintenance or style reasons, such that I would not be attempting to return an array like object?
Here is the code (which works apart from trying to return arrays);
main.cpp
/*
* Just the main class, call other classes and passes variables around
*/
#include <iostream>
#include "dropSim.h"
using namespace std;
int main()
{
double height = getHeight();
int seconds = 5;
double* results = calculateResults(height, seconds);
outputResults(results);
return 0;
}
getHeight.cpp
/*
* Asks the user for a height from which to start the experiment
* SI units
*/
#include <iostream>
using namespace std;
double getHeight()
{
cout << "What height should the experiment start at; ";
double height;
cin >> height;
return height;
}
calculateResults.cpp
/*
* given the initial height and the physical constants, the position of the ball
* is calculated at integer number seconds, beginning at 0
*/
#include "constants.h"
#include <cmath>
#include <iostream>
using namespace std;
double getPosition(double height, double time);
double* calculateResults(double height, int seconds)
{
double positions[seconds + 1];
for(int t = 0; t < seconds + 1; t++)
{
positions[t] = getPosition(height, t);
}
return positions;
}
double getPosition(double height, double time)
{
double position = height - 0.5*constants::gravity*pow(static_cast<double>(time), 2);
if( position < 0) position = 0;
//Commented code is for testing
//cout << position << endl;
return position;
}
outputResults.cpp
/*
* Takes the array of results and prints them in an appropriate format
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void outputResults(double* results){
string outputText = "";
//The commented code is to test the output method
//Which is working
//double results1[] = {1,2,3,4,5};
//int numResults = sizeof(results1)/sizeof(results1[0]);
int numResults = sizeof(results)/sizeof(results[0]);
//cout << numResults; //= 0 ... Oh
for(int t = 0; t < numResults; t++)
{
ostringstream line;
line << "After " << t << " seconds the height of the object is " << results[t] << "\r";
outputText.append(line.str());
}
cout << outputText;
}
And finally a couple of headers;
dropSim.h
/*
* dropSim.h
*/
#ifndef DROPSIM_H_
#define DROPSIM_H_
double getHeight();
double* calculateResults(double height, int seconds);
void outputResults(double* results);
#endif /* DROPSIM_H_ */
constants.h
/*
* Contains physical constants relevant to simulation.
* SI units
*/
#ifndef CONSTANTS_H_
#define CONSTANTS_H_
namespace constants
{
const double gravity(9.81);
}
#endif /* CONSTANTS_H_ */
I would say that you're over-engineering a big solution to a little problem, but to answer your specific question:
Should my program be structured differently, for performance, maintenance or style reasons, such that I would not be attempting to return an array like object?
Returning an array-like object is fine. But that doesn't mean returning an array, nor does it mean allocating raw memory with new.
And it's not restricted to return values either. When you're starting out with C++, it's probably best to just forget that it has built-in arrays at all. Most of the time, you should be using either std::vector or std::array (or another linear collection such as std::deque).
Built-in arrays should normally be viewed as a special-purpose item, included primarily for compatibility with C, not for everyday use.
It may, however, be worth considering writing your computation in the same style as the algorithms in the standard library. This would mean writing the code to receive an iterator to a destination, and writing its output to wherever that iterator designates.
I'd probably package the height and time together as a set of input parameters, and have a function that generates output based on those:
struct params {
double height;
int seconds;
};
template <class OutIt>
void calc_pos(params const &p, OutIt output) {
for (int i=0; i<p.seconds; i++) {
*output = get_position(p.height, i);
++output;
}
}
This works somewhat more clearly along with the rest of the standard library:
std::vector<double> results;
calc_pos(inputs, std::back_inserter(results));
You can go a few steps further if you like--the standard library has quite a bit to help with a great deal of this. Your calc_pos does little more than invoke another function repeatedly with successive values for the time. You could (for example) use std::iota to generate the successive times, then use std::transform to generate outputs:
std::vector<int> times(6);
std::iota(times.begin(), times.end(), 0);
std::vector<double> distances;
std::transform(times.begin(), times.end(), compute_distance);
This computes the distances as the distance dropped after a given period of time rather than the height above the ground, but given an initial height, computing the difference between the two is quite trivial:
double initial_height = 5;
std::vector<double> heights;
std::transform(distances.begin(), distances.end(),
std::back_inserter(heights),
[=](double v) { return max(initial_height-v, 0); });
At least for now, this doesn't attempt to calculate the ball bouncing when it hits the ground--it just assumes the ball immediately stops when it hits the ground.
You should get rid of self-allocated double * and use std::vector<double> instead. It's not difficult to learn and a basic step in modern C++
This is how I would solve the problem:
#include <cmath>
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::sqrt;
using std::fixed;
using std::setprecision;
using std::max;
using std::setw;
static const double g = 9.81;
class Calculator {
public:
Calculator(double inh) : h(inh)
{
}
void DoWork() const {
double tmax = sqrt(h / ( g / 2));
for (double t=0.0; t<tmax; t+=1.0) {
GenerateOutput(t);
}
GenerateOutput(tmax);
}
private:
void GenerateOutput(double t) const {
double x = g * t * t / 2;
double hremaining = max(h - x, 0.0);
cout << fixed << setprecision(2) << setw(10) << t;
cout << setw(10) << hremaining << endl;
}
double h;
};
int main() {
double h(0.0);
cout << "Enter height in meters: ";
cin >> h;
if (h > 0.0) {
const Calculator calc(h);
calc.DoWork();
} else {
return 1;
}
return 0;
}

Aggregation using C++

I am trying to make one class work with another class. It is supposed to decrement the member of the other class.
my first class is
class Bike
{
private:
int miles;
Speedometer speedom;
static int fuelCount;
public:
Bike();
Bike(int, Speedometer*); //Problem occurs here
~Bike();
int getMiles();
int getFuelCount();
void incrementMiles();
};
int Bike::fuelCount = 0;
Bike::Bike()
{
miles = 0;
fuelCount++;
}
Bike::Bike(int m, Speedometer * spm) //This is where I am having problems
{
miles = m;
speedom = &spm;
}
Bike::~Bike()
{
cout << "The Bike's destructor is running." << endl;
fuelCount--;
}
int Bike::getMiles()
{
return miles;
}
int Bike::getFuelCount()
{
return fuelCount;
}
void Bike::incrementMiles()
{
miles++;
if (miles == 999999)
miles = 0;
}
The other class which is supposed to be included in the first is:
Class Speedometer
{
private:
int fuel;
public:
Speedometer();
Speedometer(int);
~Speedometer();
int getFuel();
void incrementFuel();
void decrementFuel();
};
Speedometer::Speedometer()
{
fuel = 0;
}
Speedometer::Speedometer(int f)
{
fuel = f;
}
int Speedometer::getFuel()
{
return fuel;
}
void Speedometer::incrementFuel()
{
if (fuel <= 15)
fuel++;
}
void Speedometer::decrementFuel()
{
if (fuel > 0)
fuel--;
}
They are supposed to work together. Bike is to be able to work with speedometer object. It should decrease the speedometers current amount of fuel by one gallon for every 24 miles traveled.
This is supposed to be a aggregate relationship not composition.
Please help me just understand how to make that relationship and how its supposed to be called.
Thank you in advance.
here is my main function
btw - i have all the right #includes i just have not listed them here
int main(int argc, char *argv[])
{
Speedometer a(999970, spd);
for(int count = 0; count <=24; count++)
a.decrementMiles();
while (a.getFuel() > 0)
{
a.incrementMiles();
cout<< "Miles:" << a.getMiles() << endl;
cout<< "Fuel:" << a.getFuel() << endl;
}
return 0;
}
You have a large number of issues here.
First of all, in your main(), you construct your Speedometer object with a constructor you have not implemented. The only constructors you have defined are the default constructor and Speedometer(int). You then call Speedometer(int, ???), the ??? being spd because you do not declare spd anywhere in the code you have provided, so we have no idea what it is.
It's really impossible to say what's wrong with your code in its current state.
As written, you've made a composition; Speedometer is part of Bike since it is a field. To make it an aggregation, make Bike hold a pointer to Speedometer. Note that as a consequence, you'll probably need Bike to create or obtain an initial Speedometer (could be NULL to begin with, or pass one in the constructor), and you might want to add accessor methods to Bike in order to add/remove/change the Speedometer.
[edit] Bike might also need to know how to dispose of the Speedometer properly in order to avoid leaking it.
[edit 2] Also as #cjm571 pointed out, your main function is creating and operating directly upon a "disembodied" Speedometer. Shouldn't it be on a Bike? :)
#include <iostream>
using namespace std;
class Bike
{
private:
int miles;
static int fuelCount;
// Speedometer speedom;
public:
Bike();
Bike(int); // Speedometer *); check comment on line 82
~Bike();
int getMiles();
int getFuelCount();
void incrementMiles();
};
int Bike::fuelCount = 0;
Bike::Bike()
{
miles = 0;
fuelCount++;
}
Bike::Bike(int m)//Speedometer (*spm) I don't see the purpose of this in the current state of the program, I may not be seing the whole picture
{
miles = m;
/* speedom = spm; remember, there must be a parent and a child class, at the current state you'r trying
to call a child from parent, the child class has not been defined, so i switched them and now Bike is a chiled. */
}
Bike::~Bike()
{
cout << "The Bike's destructor is running." << endl;
fuelCount--;
}
int Bike::getMiles()
{
return miles;
}
int Bike::getFuelCount()
{
return fuelCount;
}
void Bike::incrementMiles()
{
miles++;
if (miles == 999)
miles = 0;
}
class Speedometer
{
private:
int fuel;
public:
Speedometer();
Speedometer(int f);
int getFuel();
Bike theBike; // This is what you needed in order to make incrementMiles to work.
void incrementFuel();
void decrementFuel();
};
Speedometer::Speedometer()
{
fuel = 0;
}
Speedometer::Speedometer(int f)
{
fuel = f;
}
int Speedometer::getFuel()
{
return fuel;
}
void Speedometer::incrementFuel()
{
if (fuel <= 15)
fuel++;
}
void Speedometer::decrementFuel()
{
if (fuel > 0)
fuel--;
}
int main(int argc, char *argv[])
{
Speedometer a(999); //You never declared this, did you mean spm???
for(int count = 0; count <=24; count++)
a.theBike.incrementMiles();
while (a.getFuel() > 0)
{
a.theBike.incrementMiles();
cout<< "Miles:" << a.theBike.getMiles() << endl;
cout<< "Fuel:" << a.getFuel() << endl;
}
cin.get();
return 0;
} //There is no break declared (that i can see at least) so the program runs an infinite loop
// Don't want to add too many things to it, I don't know what your plan is.
// Hoping to have made it clearer.