I have some question for coding C++ program with header file.
This is my header.h file :
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
And this is my Question1.cpp file which store all the methods:
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((width * 2) + (length * 2)) ;
}
double Rectangle::get_area()
{
return (width * length);
}
void Rectangle::resize(double factor)
{
width *= factor;
length *= factor;
}
private:
double width;
double length;
double area;
double factor;
};
And lastly, here is my main method.cpp :
#include <iostream>
#include "header.h";
using namespace std;
int main()
{
Rectangle rectangle1(2.5,7.0);
cout << rectangle1.get_perimeter();
cout << rectangle1.get_area();
system("PAUSE");
return 0;
}
However, when I try to run the program, the system told me that there was build errors and unresolved externals which I have no idea why is it so. Could somebody please help me fix it?
Thanks in advance.
Your implementations should not look like
class Rectangle
{
public:
Rectangle(double width, double length) { .... }
but like
Rectangle::Rectangle(double width, double length) : width(width), length(length) {}
You need to include header.h in the implementation .cpp file and in any file that needs the definition of the Rectangle class. You also need include guards in your headers. And do not put using namespace std in a header. In fact, don't put it anywhere.
Change .h to ->
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
Then .cpp to->
#include <iostream>
#include "header.h"
using namespace std;
Rectangle::Rectangle(double width, double length)
{
this->width = width; //I have no idea how to use this.something as its in Java
this->length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((this->width * 2) + (this->length * 2)) ;
}
double Rectangle::get_area()
{
return (this->width * this->length);
}
void Rectangle::resize(double factor)
{
this->width *= factor;
this->length *= factor;
}
This should work then.
Regards,
Luka
Few things to unpick here.
1) use this->width which is equivalent to java's this.width (In C++, this is a pointer). Actually some C++ programmers (including me) prefix member variables with m_. Then you can just write m_width = width.
2) include "header.h" at the top of Question1.cpp
3) avoid putting "using namespace std" in a header file, or you could get unintended namespace
clashes as your code expands. OK to put it in the separate source files though although some folk even discourage this.
4) depending on your compiler and linker, you'll need to link to various lib's that the iostream library uses. Perhaps if you tell us the compiler you're using, we can help you here.
5) you need to surround your header with
#ifndef ARBITRARY_TEXT_BUT_DISTINCT_FROM_ANY_OTHER_IN_YOUR_PROGRAM
#define ARBITRARY_TEXT_BUT_DISTINCT_FROM_ANY_OTHER_IN_YOUR_PROGRAM
...your code here
#endif
This is an include guard - helps prevent multiple inclusion of a header file contents.
In Question1.cpp you have to include header.h
And don't forget include guards in header.h
Also in Question1.cpp you must change
Rectangle(double width, double length)
to
Rectangle::Rectangle(double width, double length)
You need to tell your build system to compile "question1.cpp". Usually there is an "add existing file to project" menu item somewhere under "File".
And typically, your class and constructor would use a different name than the input parameter. Many people put a prefix at the begginning (mLength, iLength) or postfix at the end (length_ is common).
The other solution is to prefix the member variable with this->length, but that can get pretty messy after a while.
the big mistake that in the .cpp file you are supposed to implement only the methods not rewrite full class implementation try the following in .cpp file
Rectangle::Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
and don't include the methods in class{}; block and don't redefine your member variables
also don't forget to include the header file in the .cpp file
thanks
I wonder if you are getting linker errors as your cpp file is little weird
In the cpp file include the .h file and only implement the functions like
Rectangle::Rectangle(double width, double length){
//implement
}
double Rectangle::get_perimeter(){
//implement
}
double Rectangle::get_area(){
//implement
}
void Rectangle::resize(double factor){
//implement
}
When you want to split your class file into a *.cpp and a *.h file it always has the following form:
rectangle.h:
#ifndef __RECTANGLE_H_
#define __RECTANGLE_H_
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
#endif
now the rectangle.cpp should have the following form:
#include <iostream>
#include "rectangle.h"
using namespace std;
Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((width * 2) + (length * 2)) ;
}
double Rectangle::get_area()
{
return (width * length);
}
void Rectangle::resize(double factor)
{
width *= factor;
length *= factor;
}
so when as an explanation:
The header file tells you which fields and methods are available and the *.cpp file implements the methods.
In your main.cpp you just need o include the rectangle.h
this code below works
#include<iostream>
#include<iomanip>
using namespace std;
class student
{
private:
int area;//hours;
float perimeter;//gpa;
public:
void addcourse(int len, float wid)
{
float sum;
sum = area * perimeter;
area += len;
sum += wid * len;
perimeter = sum / area;
}
student() // constructor
{
area = 0;
perimeter= 0.0;
}
};
int main()
{
student s;
int length;//classhours;//l
float width;//classgpa;//w
cout << "Enter length ( 1 to end): ";
cin >> length;
while(length != 1)
{
cout << "Enter width: ";
cin >> width;
s.addcourse(length, width);
cout << "Enter length ( 1 to end): ";
cin >> length;
}
// cout << "Rectangle's length = " << r.getlength() << endl;
// cout << "Rectangle's width = " << r.getwidth() << endl;
// cout << "Rectangle's area = " << r.getarea() << endl;
// cout << "Rectangle's perimeter = " << r.getperimeter() << endl;
}
Related
Hello I am a student learning c++ and I am just starting to learn OOP. The problem is in my MAIN however I am showing all of my files in case it is from another file.
I have written my hpp and cpp file and now I am just working on my main for testing. The class is called Box and when I create an object box1 or box 2 and attempt to access my functions it says there are two few arguments. It says this regardless of whether I put box1.calcVolume(double h, double w, double l) or box1.calcVolume();
So the issue is on the line(s) that say:
double volume2 = box2.calcVolume();
double volume1 = box1.calcVolume();
double surfaceArea1 = box1.calcSurfaceArea();
If anyone can spot something that I missing our may not understand please let me know.
This is the header file:
#pragma once
#include <iostream>
#ifndef BOX_HPP
#define BOX_HPP
class Box
{
private:
double height;
double width;
double length;
public:
void setHeight(double h);
void setWidth(double w);
void setLength(double l);
double calcVolume(double h, double w, double l);
double calcSurfaceArea(double h, double w, double l);
Box();
Box(double height, double width, double length);
};
#endif
This is the CPP file
#include <iostream>
#include "Box.hpp"
Box::Box()
{
setHeight(1);
setWidth(1);
setLength(1);
}
Box::Box(double h, double w, double l)
{
setHeight(h);
setWidth(w);
setLength(l);
}
void Box::setHeight(double h)
{
height = h;
}
void Box::setWidth(double w)
{
width = w;
}
void Box::setLength(double l)
{
length = l;
}
double Box::calcVolume(double h, double w, double l)
{
double volume;
volume = h * w * l;
return volume;
}
double Box::calcSurfaceArea(double h, double w, double l)
{
double surfaceArea;
surfaceArea = 2 * (h*w) + 2 * (h*l) + 2 * (l*w);
return surfaceArea;
}
my BoxMain file:
#include <iostream>
#include "Box.hpp"
using std::cout;
using std::cin;
using std::endl;
int main()
{
Box box1(1.1, 2.4, 3.8);
Box box2;
box2.setHeight(12);
box2.setWidth(22.3);
box2.setLength(2.3);
double volume2 = box2.calcVolume();
double volume1 = box1.calcVolume();
double surfaceArea1 = box1.calcSurfaceArea();
cout << box1.calcVolume(); << endl; //testing different methods
return 0;
}
Your method takes three parameters:
double Box::calcVolume(double h, double w, double l)
{
double volume;
volume = h * w * l;
return volume;
}
So, you would call it like so:
Box b;
double volume = b.calcVolume(1, 2, 3);
But that's not quite right. An instance of Box knows how big it is, because you pass a size to the constructor, which stores the sizes in the fields width, height, and length. You probably want something like this:
double Box::calcVolume()
{
volume = height * width * length;
return volume;
}
You have the code wrong. The dimensions of the box are known during the creation of box object. The length, width and height are already available - updated in the member variables.
Functions calcVolume and calcSurfaceArea should not take arguments but return the computed value. Modified code below:
double Box::calcVolume()
{
return height*width*length;
}
double Box::calcSurfaceArea()
{
return 2*((height*width) + (height*length) + (length*width));
}
Also, remember to modify the .hpp file with the declarations corresponding to the code above.
Declaration in the .hpp file should be
double calcVolume();
double calcSurfaceArea();
I have solved the problem. I removed the arguments in calcVolume and calcSurfaceArea everywhere in my code and it resolved the error.
This program contains three parts: the header, the functions for the class and the main part that is interactive. However, it won't compile.
I keep getting the response that there is an expected constructor, destructor or type conversion.
#ifndef BOX_H
#define BOX_H
class Box
{
private:
double height;
double width;
double length;
public:
Box();
double setHeight();
double setWidth();
double setLength();
double getVolume();
double getSurfaceArea();
};
#endif
function.cpp:
#include "Box.hpp"
/**********************************************************************
Box:: Box
This is the default constructor that uses the set methods to initialize each field to 1.
* **********************************************************************/
Box::Box()
{
height = 1;
width = 1;
length = 1;
}
/*
Does anyone know what this section does? Is it another default constructor or is is it even needed?
Box::Box(double height, double width, double length)
{
setHeight(height);
setWidth(width);
setLength(length);
}
*/
double Box::setHeight()
{
return height;
}
double Box::setWidth()
{
return width;
}
double Box::setLength()
{
return length;
}
double Box::getVolume()
{
return height * width * length;
}
double Box::getSurfaceArea()
{
double SurAre = 0;
SurAre = (2 * (length * width)) + (2 * (length * height)) + (2 * (height * width));
return SurAre;
}
main.cpp:
#include <iostream>
#include "Box.hpp" //contains Box class declaration
using namespace std;
int main()
{
Box object;
double Alength;
double Awidth;
double Aheight;
cout << "This program will calculate the area of a box.\n";
cout << "What is the length?";
cin >> Alength;
cout << "What is the width?";
cin >> Awidth;
cout << "What is the height?";
cin >> Aheight;
object.setLength(Alength);
if (!object.setWidth(Awidth))
cout << "Invalid box width entered. \n" << endl;
if (!object.setHeight(Aheight))
cout << "Invalid box height entered. \n" << endl;
cout << "Volume: " << object.getVolume() << endl;
cout << "Surface Area: " << object.getSurfaceArea() << endl;
return 0;
}
Does anyone have an idea about why?
If you uncomment the three-parameter constructor, you will get an error message, because a constructor is a class member, and class members have to be declared inside the class before they can be used or defined outside.
Add the line
Box(double height, double width, double length);
inside your class definition, and then the additional constructor can be compiled also.
C++ has some strange behaviors: if you fail to declare and define a default constructor, it will do it for you. Think autogenerated. It will also define a compiler-generated copy constructor and destructor. It's helpful to understand this, because these things exist whether you define them or not.
You both declared the constructor in the header:
public:
Box();
and defined it in the cpp file:
Box::Box()
You correctly both declared and defined this constructor.
If you want any other constructor, you have to declare it before you can define it as well
public:
Box();
Box(double height, double width, double length); // this is new
and then you can uncomment your definition in the cpp file, and all should be well.
One other style point: the way you've defined your 3 parameter constructor is not great style. What happens is that you construct a Box, and when you do so, you use the default constructor for it's member variables of height, width, and depth. You then call 3 member functions to assign these variables. In C++ you can avoid all this by using an initializer list. The body of your 3 parameter constructor becomes
Box::Box(double height, double width, double length) :
height(height), width(width), length(length)
{}
What this says is "build me a Box, and as you do so, use the value of passed in height for member height, width for member width, length for member length". You save yourself an assignment of 0 as a default value for the member variables and 3 function calls by building your Box "out of the box" as it were with those values. This uses the copy constructor for your member variables rather than their default constructors followed by an assignment.
(technical note: as builtins, doubles technically don't have these constructors, but the semantics behave as if they do, so you can think of them as having them on first order thought.)
This means, additionally, that if you define a copy constructor:
Box(const Box& other);
then you can use that in other classes to initialize a Box in their initializer lists, e.g.
BunchOfBoxes(const Box& firstBox) :
m_firstBox(firstBox)
{}
and it will use your copy constructor from the Box class to do the same sort of initialize-on-build for BunchOfBoxes
You have a problem with your class declaration/definition:
Your setters should have parameters so you can use them as setters.
In your Box.hpp change
double setHeight();
double setWidth();
double setLength();
to
double setHeight(double _height);
double setWidth(double _width);
double setLength(double _length);
Then in your Box.cpp change
double Box::setHeight()
{
return height;
}
double Box::setWidth()
{
return width;
}
double Box::setLength()
{
return length;
}
to
double Box::setHeight(double _height)
{
height = _height;
return height;
}
double Box::setWidth(double _width)
{
width = _width;
return width;
}
double Box::setLength(double _length)
{
length = _length;
return length;
}
My program is supposed to calculate the surface area and volume of a box. I am to have the following functions: setHeight, setWidth, setLength, getVolume, getSurfaceArea.
When I compile my program I get the following error message:
boxMain.cpp: In function ‘int main()’:
boxMain.cpp:21: error: no matching function for call to 'Box::getVolume(double&, double&, double&)’
Box.hpp:20: note: candidates are: double Box::getVolume()
boxMain.cpp:23: error: no matching function for call to ‘Box::getSurfaceArea(double&, double&, double&)’
Box.hpp:21: note: candidates are: double Box::getSurfaceArea()
Based on my searches on this site, most answers seem to suggest that the default constructor doesn't exit or isn't working. I don't know if that is my issue as well, but I wrote the code for my default constructor according to textbook, so I have trouble figuring out what I did wrong.
The missing lines in my code below are just the descriptions and comments that I removed.
Any help would be appreciated! Thank you all so much in advance.
Here is my .hpp file:
#include <iostream>
#ifndef Box_HPP
#define BOX_HPP
class Box {
private:
double h, w, l;
double height, width, length;
public:
void setHeight(double h);
void setWidth(double w);
void setLength(double l);
double getVolume();
double getSurfaceArea();
Box();
};
Here is my function .cpp file:
#include <iostream>
#include <iomanip>
#include "Box.hpp"
double height;
double width;
double length;
Box::Box() {
height = 1.0;
width = 1.0;
length = 1.0;
}
void setHeight(double h) {
if(h < 0) {
std::cout << "Error. Height must be positive."
<< std::endl;
}
else {
height = h;
}
}
void setWidth(double w) {
if(w < 0) {
std:: cout << "Error. Width must be positive."
<< std::endl;
}
else {
width = w;
}
}
void setLength(double l) {
if(l < 0) {
std::cout << "Error. Length must be positive."
<< std::endl;
}
else {
length = l;
}
}
double getVolume() {
return (height * width * length);
}
double getSurfaceArea() {
return (2.0 * length * height + 2.0 * width * height);
}
Here is my main .cpp file:
#include <iostream>
#include <fstream>
#include "Box.hpp"
int main() {
Box box1;
double h, w, l;
std::cout << "Enter height" << std::endl;
std::cin >> h;
std::cout << "Enter width" << std::endl;
std::cin >> w;
std::cout << "Enter length" << std::endl;
std::cin >> l;
void setHeight(double h);
void setWidth (double w);
void setLength (double l);
std::cout << "volume: "
<< box1.getVolume(h, w, l) << std::endl;
std::cout << "surface: "
<< box1.getSurfaceArea(h, w, l) << std::endl;
return 0;
}
Box::getVolume is declared as taking no parameters, but in line 21 you call it with 3 arguments:
box1.getVolume(h, w, l)
Use simply box1.getVolume() instead. Similarly for Box::getSurface().
Also, use Box:: in front of all member function definitions, like void Box::setHeight(double h) {...}, otherwise you end up defining free standing functions and you'll get linker errors since the member functions end up not defined.
vsoftco's answer is mostly correct so I have up voted him, although I feel it would be good to add some more information to the answer to help explain it a bit better as well as help clean up several other issues you have here.
The error you had clearly explains the problem if you look at it. It mentions boxMain.cpp in the function int main() as having the problem. It further gives you the line number and mentions that there is "no matching function" for the "call" and in both instances notes the call as well as the possible candidates, which in this case is the methods without parameters.
with that aside here are some other tips that may help you avoid further frustration:
Prefer forward declarations instead of includes in your header files. In your case you don't need #include <iostream> at all in your box.hpp. The reason is that anything in your header is effectively leaked into any files that include your header. This is mainly to help reduce circular dependancies as well as shorten compile times when making changes. The Pimpl Idiom is an example pattern used with this mantra. I would not recommend using naked pointers, however, instead stick with RAII types such as smart pointers or plain references.
You either didn't paste all of your code or your include guard is wrong. You need a closing #endif in your header.
You should use a convention to name your member variables to avoid conflicts and keep your large .cpp files easier to read. This is a preference more then a rule but it helps. Something like _height, mHeight, _mHeight rather then height. Lower case camel style variable names are common for locals and parameters. It also looks like you really don't need the h,w,l members at all.
You should probably use assert for your error handling so as to optimize it out during release builds. That is of coarse unless you are intending to show the end user the error message. You may also consider using std::cerr instead.
The height, width, length variables in your .cpp are also extraneous and do not do what you think.
You should use an initialization list in your constructor instead of doing the simple work of assigning to variables in the body. There are several special situations as well but this can get you started.
ex: Box::Box() : height(1.0), width(1.0), length(1.0){}
The only method in the cpp you fully qualified with Box:: is the constructor. You need to do that with all the methods as well. ex: double Box::getVolume()
You are also not calling the correct methods in your main function (in fact you are not calling methods at all. You are basically forward declaring them.) you should be using an object to invoke the methods. This is why you didn't see a complaint in the error log about missing Box::
There is one major error in your header file that has nothing to do with your class's declaration, but has to do with the header during the pre-compilation stage. Your header guard is not correct as you have first have your #include <iostream> before the guard; this should be after the guard. Second your #ifndef CLASS_NAME does not match your #define CLASS_NAME and you are missing the matching #endif at the bottom of your header file. I will remove the #include <iostream> since it is not needed. The reason I am doing this is because if a user enters a value that is less than or equal to zero it will be set to a default value of 1. So there is no need to print out any error messages for this class.
Your class is close to what you need. There are a few things that would help to improve your class and maybe this will help.
Box.h
#ifndef BOX_H
#define BOX_H
class Box {
private:
double m_width;
double m_length;
double m_height;
double m_volume;
double m_surfaceArea;
public:
Box(); // Default Constructor
Box( double width, double length, double height );
// virtual ~Box(); // Default Okay
void setWidth( double width );
void setLength( double length );
void setHeight( double height );
double getWidth() const;
double getLegnth() const;
double getHeight() const;
double getVolume() const;
double getSurfaceArea() const;
private:
// If You Need Either The Copy Constructor Or The Assignment Operator
// Remove Them From The Private Section Into The Public Section
// Where You May Need To Implement Them Where The Default May Not Be Appropriate
Box( const Box& c ); // Not Implemented
Box& operator=( const Box& c ); // Not Implemented
void calculateVolume();
void calculateSurfaceArea();
}; // Box
#endif // BOX_H
Box.cpp
#include "Box.h"
// -------------------------------------------------------------------------
// Box() - Default Box Will Have a 1 x 1 x 1 Dimension
Box::Box() :
m_width( 1.0 ),
m_length( 1.0 ),
m_height( 1.0 ),
m_volume( 0.0 ),
m_surfaceArea( 0.0 ) {
calculateVolume();
calculateSuraceArea();
} // Box
// -------------------------------------------------------------------------
// Box() - User Defined Constructor
Box::Box( double width, double length, double height ) :
m_volume( 0.0 ),
m_surfaceArea( 0.0 ) {
if ( width <= 0 ) {
m_width = 1.0;
} else {
m_width = width;
}
if ( length <= 0 ) {
m_length = 1.0;
} else {
m_length = length;
}
if ( height <= 0 ) {
m_height = 1.0;
} else {
m_height = height;
}
calculateVolume();
calculateSurfaceArea();
} // Box
// -------------------------------------------------------------------------
// setWidth()
void Box::setWidth( double width ) {
// First Check To See If Value Passed In Is Same Member Value
if ( width == m_width ) {
// Nothing To Do
return;
} else if ( width <= 0 ) {
m_width = 1.0
} else {
m_width = width;
}
calculateVolume();
calculateSurfaceArea();
} // setWidth
// -------------------------------------------------------------------------
// setLength()
void Box::setLength( double length ) {
// First Check To See If Value Passed In Is Same Member Value
if ( length == m_length ) {
// Nothing To Do
return;
} else if ( length <= 0 ) {
m_length = 1.0
} else {
m_length = length;
}
calculateVolume();
calculateSurfaceArea();
} // setLength
// -------------------------------------------------------------------------
// setHeight()
void Box::setHeight( double height ) {
// First Check To See If Value Passed In Is Same Member Value
if ( height == m_height ) {
// Nothing To Do
return;
} else if ( height <= 0 ) {
m_height = 1.0
} else {
m_height = height;
}
calculateVolume();
calculateSurfaceArea();
} // setHeight
// -------------------------------------------------------------------------
// getWidth()
double Box::getWidth() const {
return m_width;
} // getWidth
// -------------------------------------------------------------------------
// getLength()
double Box::getLength() const {
return m_length;
} // getLength
// -------------------------------------------------------------------------
// getHeight()
double Box::getHeight() const {
return m_height;
} // getHeight;
// -------------------------------------------------------------------------
// getVolume()
double Box::getVolume() const {
return m_volume;
} // getVolume
// -------------------------------------------------------------------------
// getSurfaceArea()
double Box::getSurfaceArea() const {
return m_surfaceArea;
} // getSurfaceArea
// -------------------------------------------------------------------------
// calculateVolume()
void Box::calculateVolume() {
m_volume = m_width * m_length * m_height;
} // calculateVolume
// -------------------------------------------------------------------------
// calculateSurfaceArea()
void Box::calculateSurfaceArea {
m_dSurfaceArea = (m_width * m_length * 2) +
(m_width * m_height * 2) +
(m_length * m_height * 2);
} // calculateSurfaceArea
With the design of this class the calculations for both the volume and surface area are private to this class only for all they do is an internal calculation that get saves into the classes member variable where there are public access methods available to retrieve them. Also each of the 3 dimensional setters does the same check as both constructors for values that are less than and equal to 0 and if so will default them to 1.
If the value that is passed into any of the setter functions is the same that is already stored the function will do nothing and just return. If the value is greater than 0 and is not equal to what is already saved, it will overwrite the member variable and call both of the private calculate methods to update the volume and surface area.
Now if you want to improve this for better performance then you can declare both calculate methods as inline, move them out of the cpp file and either add them into the header file after your class declaration and before the #endif or you can add an `#include "Box.inl" and just create another header file type with the same name as the class except with the inl extension and cut and paste these two functions in there.
I wrote code in C++ in Xcode and receive:
error: ‘cylinder’ was not declared in this scope
Header file cylinder.h:
#include <iostream>
#ifndef cylinder_h
#define cylinder_h
#endif
#include "stdio.h"
using namespace std;
class cylinder
{
public:
// Constructors
cylinder();
cylinder(double r, double h);
// Accessors
double getRadius();
double getHeight();
void setRadius(double r);
void setHeight(double h);
double area();
double volume();
void write(std::ostream& output);
private:
double radius;
double height;
};
cylinder.cpp :
#include "cylinder.h"
double PI = 3.1415926535898;
#include "stdio.h"
using namespace std;
// Constructors
cylinder::cylinder()
{
radius = 0;
height = 0;
}
cylinder::cylinder(double r, double h)
{
radius = r;
height = h;
}
// Accessors
double cylinder::getRadius()
{
return radius;
}
double cylinder::getHeight()
{
return height;
}
// Setters
void cylinder::setRadius(double r)
{
radius = r;
}
void cylinder::setHeight(double h)
{
height = h;
}
// Calculations
double cylinder::area()
{
return 2 * PI * radius * radius + 2 * PI * radius * height;
}
double cylinder::volume()
{
return PI * radius * radius * height;
}
main.cpp:
#include <iostream>
using namespace std;
#include <string>
#include "cylinder.h"
#include <iomanip>
#include "sphere.h"
#include "prism.h"
#include "cone.h"
#include "pyramid.h"
#include <cstdlib>
int main()
{
double radius, height,sradius,length,width,rheight,cheight,cradius,pheight,plength;
cout << "Enter cylinder height and radius >>> ";
cin >> height >> radius;
cylinder one (radius, height);
cout << "The cylinder volume is " << setprecision(2)<<fixed<<one.volume () << endl;
cout << "The cylinder surface area is " << setprecision(2)<<fixed<<one.area () << endl;
cout <<"CYLINDER: "<<height<<", "<<radius<<endl;
}
I have been stuck for two days. I am so confused. I've already defined cylinder class, and I've tried many ways on the website. Is there anyone who can help me?
It's due tonight!
Sadly a method to try to find the answer and not the answer. It has been posted as an answer because I don't think I can fit it all in the bounds of a comment.
I have removed that which has not been provided, corrected the use if the include guard, shuffled a few things around, and commented out that which was not needed. Hopefully I have left a good enough explanation of what I did and why. If not, ask.
This compiles. I have not tested the logic.
What to do with it:
In main.cpp there are a bunch of files that were included but not provided. To get a working base, I have commented them out. Add them and rebuild the program one by one until the program stops compiling. If this does not make the problem obvious, it has at least reduced the search area.
Revised cylinder.h
// two lines below are an include guard. It prevents a header file from being included
// multiple times, heading off potentially recursive includes (a loop that
// causes the compiler to go forever) and chaos caused by redefining the same
// stuff multiple times.
#ifndef cylinder_h
#define cylinder_h
#include <iostream>
//#include "stdio.h" unused and should be #include <cstdio> when used in C++
//using namespace std; unused and very dangerous.
class cylinder
{
public:
// Constructors
cylinder();
cylinder(double r, double h);
// Accessors
double getRadius();
double getHeight();
void setRadius(double r);
void setHeight(double h);
double area();
double volume();
void write(std::ostream& output);
private:
double radius;
double height;
};
#endif // end of include guard moved to here
Revised cylinder.cpp
#include "cylinder.h"
double PI = 3.1415926535898;
//#include "stdio.h" not used
//using namespace std; dangerous and not used.
// Constructors
cylinder::cylinder()
{
radius = 0;
height = 0;
}
cylinder::cylinder(double r, double h)
{
radius = r;
height = h;
}
// Accessors
double cylinder::getRadius()
{
return radius;
}
double cylinder::getHeight()
{
return height;
}
// Setters
void cylinder::setRadius(double r)
{
radius = r;
}
void cylinder::setHeight(double h)
{
height = h;
}
// Calculations
double cylinder::area()
{
return 2 * PI * radius * radius + 2 * PI * radius * height;
}
double cylinder::volume()
{
return PI * radius * radius * height;
}
Revised main.cpp
#include <iostream>
//#include <string> not needed
#include "cylinder.h"
#include <iomanip>
// the following headers were not provided and may be containing bad code that
// breaks the OP's build. No way to tell. Add one and rebuild. If the program still
//compiles, the problem is likely elsewhere so add another and rebuild.
//#include "sphere.h"
//#include "prism.h"
//#include "cone.h"
//#include "pyramid.h"
//#include <cstdlib> not used
//using namespace std; used but use with caution. Instead, use only the pieces you need
using std::cout;
using std::cin;
using std::setprecision;
using std::fixed;
using std::endl;
// or explicitly state the namespace at each use.
// Eg. std::cout << "blah blah blah" << std::endl;
int main()
{
double radius, height;//,sradius,length,width,rheight,cheight,cradius,pheight,plength;
cout << "Enter cylinder height and radius >>> ";
cin >> height >> radius;
cylinder one (radius, height);
cout << "The cylinder volume is " << setprecision(2)<<fixed<<one.volume () << endl;
cout << "The cylinder surface area is " << setprecision(2)<<fixed<<one.area () << endl;
cout <<"CYLINDER: "<<height<<", "<<radius<<endl;
}
try to put #endif at the end of the header file
I think it's because of your multiples "using namespace std" , use only one , that one in the header file , and be sure to put it after all #includes
Here's your original code in a form that compiles and runs on my gnu/linux system. I tried to not to make many changes. I think you'll benefit from comparing your old code with new code to see what the minimal changes are, this may clear up some things for you.
After that, I show a more cleaned up version of the code, again I haven't really corrected it, especially the style and features used, but I've just tried to cut away a lot of the unnecessary things. I think realising what isn't neeed may also clear up some issues for you.
Code with minimal changes:
cylinder.h:
#include <iostream>
#ifndef cylinder_h
#define cylinder_h
#endif
#include "stdio.h"
using namespace std;
class cylinder
{
public:
// Constructors
cylinder();
cylinder(double r, double h);
// Accessors
double getRadius();
double getHeight();
void setRadius(double r);
void setHeight(double h);
double area();
double volume();
void write(std::ostream& output);
private:
double radius;
double height;
};
cylinder.cpp:
#include "cylinder.h"
double PI = 3.1415926535898;
#include "stdio.h"
using namespace std;
// Constructors
cylinder::cylinder()
{
radius = 0;
height = 0;
}
cylinder::cylinder(double r, double h)
{
radius = r;
height = h;
}
// Accessors
double cylinder::getRadius()
{
return radius;
}
double cylinder::getHeight()
{
return height;
}
// Setters
void cylinder::setRadius(double r)
{
radius = r;
}
void cylinder::setHeight(double h)
{
height = h;
}
// Calculations
double cylinder::area()
{
return 2 * PI * radius * radius + 2 * PI * radius * height;
}
double cylinder::volume()
{
return PI * radius * radius * height;
}
main.cpp:
#include <iostream>
using namespace std;
#include <string>
#include "cylinder.h"
#include <iomanip>
#include <cstdlib>
int main()
{
double radius, height,sradius,length,width,rheight,cheight,cradius,pheight,plength;
cout << "Enter cylinder height and radius >>> ";
cin >> height >> radius;
cylinder one (radius, height);
cout << "The cylinder volume is " << setprecision(2)<<fixed<<one.volume () << endl;
cout << "The cylinder surface area is " << setprecision(2)<<fixed<<one.area () << endl;
cout <<"CYLINDER: "<<height<<", "<<radius<<endl;
}
Here's the code with a bit more cleanup:
cylinder.h:
#ifndef cylinder_h
#define cylinder_h
#include <iostream>
class cylinder
{
public:
// Constructors
cylinder();
cylinder(double r, double h);
// Accessors
double getRadius();
double getHeight();
void setRadius(double r);
void setHeight(double h);
double area();
double volume();
void write(std::ostream& output);
private:
double radius;
double height;
};
#endif
cylinder.cpp:
#include "cylinder.h"
static const double PI = 3.1415926535898;
// Constructors
cylinder::cylinder() : radius(0.0), height(0.0)
{
}
cylinder::cylinder(double r, double h) : radius(r), height(h)
{
}
// Accessors
double cylinder::getRadius()
{
return radius;
}
double cylinder::getHeight()
{
return height;
}
// Setters
void cylinder::setRadius(double r)
{
radius = r;
}
void cylinder::setHeight(double h)
{
height = h;
}
// Calculations
double cylinder::area()
{
return 2 * PI * radius * radius + 2 * PI * radius * height;
}
double cylinder::volume()
{
return PI * radius * radius * height;
}
main.cpp:
#include <iostream>
#include <string>
#include <iomanip>
#include "cylinder.h"
using namespace std;
int main()
{
double radius, height;
cout << "Enter cylinder height and radius >>> ";
cin >> height >> radius;
cylinder one(radius, height);
cout << "The cylinder volume is " << setprecision(2) << fixed << one.volume() << endl;
cout << "The cylinder surface area is " << setprecision(2) << fixed << one.area() << endl;
cout << "CYLINDER: " << height << ", " << radius << endl;
}
How to correct this code, its not working properly.
length and width is not getting the correct values.
I'm having problem where I declared Rectangle::get().
#include<iostream>
using namespace std;
class Rectangle{
protected:
double length;
double width;
public:
void setter(double len, double wid)
{
length = len;
width = wid;
}
double get()
{
return length*width;
}
};
class Block: public Rectangle{
private:
double heigth;
public:
void setter_h(double hei)
{
heigth = hei;
}
double get_1()
{
return(heigth * Rectangle::get());//this is the problem
}
};
int main()
{
double len, hei, wid;
cout<<"Enter the length: ";
cin>>len;
cout<<"Enter the Width: ";
cin>>wid;
cout<<"Enter the H: ";
cin>>hei;
Rectangle R1;
R1.setter(len,wid);
cout<<"Area: " << R1.get();
Block B1;
B1.setter_h(hei);
cout<<"Volume: "<< B1.get_1();
}
Can someone please help me???
im totaly confused because i think i have written right code but its giving garbage value for volume.
Because you didn't set the width and length for B1. You should also call
B1.setter(len, wid);
before calling B1.get_1().