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;
}
Related
Vehicle class is an abstract base class for ElectricVehicle and GasolineVehicle classes, and HybridVehicle class inherits from ElectricVehicle and GasolineVehicle.
I have two 'Vehicle':base class undefined errors in ElectricVehicle.h and GasolineVehicle.h. I know I am messing up the #include files somehow, but I'm having trouble figuring that out.
I tried removing the Vehicle.cpp in ElectricVehicle.cpp and GasolineVehicle.cpp and adding the Vehicle header file, but that came up with a bunch of other errors.
Vehicle.h
#pragma once
#ifndef Vehicle_h
#define Vehicle_h
class Vehicle {
public:
// check here // 4 lines
float engineEfficiency;
virtual float calculateRange() = 0;
virtual float percentEnergyRemaining() = 0;
virtual void drive(float) = 0;
virtual ~Vehicle();
};
#endif
Vehicle.cpp
#pragma once
#include "Vehicle.h"
#include <iostream>
using namespace std;
Vehicle::~Vehicle() {
cout << "In vehicle destructor" << endl;
}
ElectricVehicle.h
#pragma once
#include <iostream>
#ifndef ElectricVehicle_h
#define ElectricVehicle_h
class ElectricVehicle : virtual public Vehicle {
public:
float maximumCharge;
float currentCharge;
float engineEfficiency;
public:
ElectricVehicle(float max, float eff);
float calculateRange();
float percentEnergyRemaining();
void drive(float km);
~ElectricVehicle();
};
#endif
ElecticVehicle.cpp
#pragma once
#include "Vehicle.cpp"
#include "ElectricVehicle.h"
using namespace std;
ElectricVehicle::ElectricVehicle(float maxEnergy, float rating) {
engineEfficiency = rating;
maximumCharge = maxEnergy;
currentCharge = maxEnergy;
}
ElectricVehicle::~ElectricVehicle() {
cout << "In Electric vehicle destructor" << endl;
}
float ElectricVehicle::calculateRange() {
return (currentCharge * 100 / engineEfficiency);
}
float ElectricVehicle::percentEnergyRemaining() {
return (currentCharge * 100.0f / maximumCharge);
}
void ElectricVehicle::drive(float km) {
if (currentCharge < 0) {
cout << "Your Car is out of energy";
return;
}
currentCharge -= (km / 100) * engineEfficiency;
}
GasolineVehicle.cpp
#include "Vehicle.cpp"
#include "GasolineVehicle.h"
using namespace std;
GasolineVehicle::GasolineVehicle(float maxEnergy, float rating) {
engineEfficiency = rating;
maximumGasoline = maxEnergy;
currentGasoline = maxEnergy;
}
GasolineVehicle::~GasolineVehicle() {
cout << "In Gasoline vehicle destructor" << endl;
}
float GasolineVehicle::calculateRange() {
return currentGasoline * 100 / engineEfficiency;
}
float GasolineVehicle::percentEnergyRemaining() {
return (currentGasoline * 100.0f / maximumGasoline);
}
void GasolineVehicle::drive(float km) {
if (currentGasoline < 0){
cout << "Your Car is out of energy";
return;
}
currentGasoline -= (km / 100) * engineEfficiency;
}
Gasoline.h
#pragma once
#include <iostream>
#ifndef GasolineVehicle_h
#define GasolineVehicle_h
class GasolineVehicle : virtual public Vehicle {
public:
float maximumGasoline;
float currentGasoline;
float engineEfficiency;
GasolineVehicle(float max, float eff);
~GasolineVehicle();
float calculateRange();
float percentEnergyRemaining();
void drive(float km);
};
#endif
HybridVehicle.cpp
#pragma once
#include "ElectricVehicle.h"
#include "GasolineVehicle.h"
#include "HybridVehicle.h"
#include<iostream>
using namespace std;
// hybridvehicle constructor is calling its parent class constructors;
HybridVehicle::HybridVehicle(float maxGasoline, float gasefficiency, float maxcharge, float electricefficiency) :GasolineVehicle(maxGasoline, gasefficiency), ElectricVehicle(maxcharge, electricefficiency) {}
HybridVehicle::~HybridVehicle() {
cout << "In Hybrid vehicle destructor" << endl;
}
// :: is scope resolution operator as both gasoline and electric vehicle classes having engine efficiency the compiler
// will be confused of which variable to take.. so we :: to remove ambuiguity
float HybridVehicle::calculateRange() {
return (currentCharge / ElectricVehicle::engineEfficiency) * 100 + (currentGasoline / GasolineVehicle::engineEfficiency) * 100;
}
float HybridVehicle::percentEnergyRemaining() {
return ((currentCharge + currentGasoline) / (maximumCharge + maximumGasoline)) * 100.0f;
}
void HybridVehicle::drive(float km) {
if (currentGasoline + currentCharge < 0) {
cout << "Your Car is out of energy";
return;
}
else if (currentCharge > 0) {
currentCharge -= (km / 100) * ElectricVehicle::engineEfficiency;
}
else
{
currentGasoline -= (km / 100) * GasolineVehicle::engineEfficiency;
}
}
HybridVehicle.h
#pragma once
#ifndef HybridVehicle_h
#define HybridVehicle_h
class HybridVehicle: public GasolineVehicle, public ElectricVehicle {
public:
HybridVehicle(float gMax, float gEff, float eMax, float eEff);
~HybridVehicle();
float calculateRange();
float percentEnergyRemaining();
void drive(float km);
};
#endif
Week2.cpp
#pragma once
#include "Vehicle.cpp"
#include "HybridVehicle.cpp"
using namespace std;
Vehicle* testVehicle(Vehicle* pVehicle, const char* vehicleName) {
cout << vehicleName << " s range is: " << pVehicle->calculateRange() << endl;
pVehicle->drive(150);
cout << vehicleName << " s energy left is: " << pVehicle->percentEnergyRemaining() << endl;
cout << vehicleName << " s range is now: " << pVehicle->calculateRange() << endl;
return pVehicle;
}
int main(int argc, char** argv)
{
//50L of gas, 7.1 L/100km
delete testVehicle(new GasolineVehicle(50, 7.1), "Corolla");
//42 L of gas, 4.3 L/100km, 8.8kWh, 22 kWh/100km
delete testVehicle((GasolineVehicle*)new HybridVehicle(42, 4.3, 8.8, 22.0), "Prius");
//75 kWh, 16 kWh/100km
delete testVehicle(new ElectricVehicle(75, 16), "Tesla 3");
return 0;
}
What is the error? How to solve it? This code is to find the area of the circle using pointers and functions. The error I am facing is that the &answer cannot be converted into float.
#include <iostream>
using namespace std;
void area(float, float);
int main()
{
float radius, answer = 0.0;
cout << "Enter a radius:"; // Take the radius from the user.
cin >> radius;
area(&radius, &answer);
cout << "Area of circle is:" << answer;
return 0;
}
void area(float *value, float *result) // This is the function to calculate the area.
{
*result = 3.142 * (*value) * (*value);
}
You can do one of the 2 things:
Change the prototype to void area(float*, float*);
Remove the prototype and move the function:
void area(float *value, float *result) // This is the function to calculate the area.
{
*result = 3.142 * (*value) * (*value);
}
above the main() function. Either of these will work.
I'm using Visual Studio 2019, and when I made my first class in C++, an error occurred. It dissappeared when I deleted #include <Windows.h>. My question is, why does Windows.h collide with C++ classes, and is it possible to use both (I'm almost sure it is).
#include <iostream>
#include <locale>
using std::cout;
using std::cin;
class Rectangle {
public:
Rectangle() = default;
Rectangle(double width, double height)
: width_{ width }, height_{ height }
{}
double Width() const { return width_; }
double Height() const { return height_; }
double Area() const {
return width_ * height_;
}
double Perimeter() const {
return 2 * (width_ + height_);
}
void Scale(double scaleFactor) {
width_ *= scaleFactor;
height_ *= scaleFactor;
}
private:
double width_{};
double height_{};
};
void printInfo(const Rectangle & r) {
cout << "Width" <<r.Width() << '\n';
cout << "Height" << r.Height() << '\n';
cout << "Area" << r.Area() << '\n';
cout << "Per" << r.Perimeter() << '\n';
}
int main() {
setlocale(LC_ALL, "pl_PL.UTF8");
Rectangle rect;
}
Windows.h defines Rectangle as a free function, see here.
Solution: change the name of your class or put it in its own namespace.
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;
}
Here is my Shape.h. Ignore all the code that is commented out. That is from a version that I believe was incorrect but I left it in there in case I was wrong.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <math.h>
#include "Point.h"
using namespace std;
class Shape {
public:
Shape() {}
virtual ~Shape() {}
/*
virtual float calcArea(const Shape& s) const = 0;
virtual float calcCircum(const Shape& s) const = 0;
virtual string calcBox(const Shape& s) const = 0;
virtual void display(const Shape& s) const = 0;
*/
virtual float calcArea() const = 0;
virtual float calcCircum() const = 0;
virtual string calcBox() const = 0;
virtual void display() const = 0;
};
class Circle : public Shape {
public:
int radius;
int pointX;
int pointY;
Point *middlePoint;
float PI;
Circle() : Shape() {
middlePoint = new Point(0,0);
radius = 0;
}
~Circle() {}
Circle(int rad, Point& p) : Shape() {
PI = 3.141592;
*middlePoint = p;
pointX = p.getX();
pointY = p.getY();
radius = rad;
}
// float calcArea(const Circle& s) const {
float calcArea() const {
float tempArea;
// tempArea = PI * s.radius * s.radius;
tempArea = PI * radius * radius;
return tempArea;
}
// float calcCircum(const Circle& s) const {
float calcCircum() const {
// int diameter = 2 * s.radius;
int diameter = 2 * radius;
float tempCircum;
tempCircum = PI * diameter;
return tempCircum;
}
// string calcBox(const Circle& s) const {
string calcBox() const {
// int x = s.pointX;
// int y = s.pointY;
// int r = s.radius;
int x = pointX;
int y = pointY;
int r = radius;
int tlX = x - r;
int tlY = y + r;
int blX = x - r;
int blY = y - r;
int trX = x + r;
int trY = y + r;
int brX = x + r;
int brY = y - r;
Point *topLeft = new Point(tlX,tlY);
Point *bottomLeft = new Point(blX,blY);
Point *topRight = new Point(trX,trY);
Point *bottomRight = new Point(brX,brY);
stringstream output;
string tempOut;
output << *topLeft << *bottomLeft << *topRight << *bottomRight;
tempOut = output.str();
return tempOut;
}
// void display(const Circle& s) const {
void display() const {
cout << "Class Name: Circle" << endl;
// float tmpArea = calcArea(s);
float tmpArea = calcArea();
cout << "Area = " << tmpArea << endl;
// cout << "Radius = " << s.radius << endl;
cout << "Radius = " << radius << endl;
// float tmpCircum = calcCircum(s);
float tmpCircum = calcCircum();
cout << "Circumference = " << tmpCircum << endl;
cout <<"Middle Point = " << middlePoint;
// string bbox = calcBox(s);
string bbox = calcBox();
cout <<"Bounding Box Points = " << bbox;
}
};
Here is my TMA4Question1.cpp code.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <math.h>
#include "Shape.h"
int main() {
Point *circlePoint = new Point(10,-5);
Circle *mainCircle = new Circle(23,*circlePoint);
}
Ok. Yes this is a homework assignment for University. I'm not looking just for the answer, I would like to know why this program gives me a segmentation fault and how to correct it.
I know the error is in the Circle code, where I pass a pointer to the circlePOint in the constructor for the Circle class. I dont know why it generates a seg fault. I hope someone can provide some insight. Thanks.
Sorry if the code is messy. Had a hard time pasting it into here properly with 4 spaces and all that.
middlePoint is not allocated in your second Circle constructor. You are assigning a value to it before giving it some memory. As an aside, I don't see why anything there needs to be a pointer.
Why do you use pointers to Points inside your classes at all? You only generate memory leaks this way and (without your own copy operations) cause problems with as the midpoints could be shared by different circles.
PS: And it's not needed to have a PI value (even as non-const) in every circle - just use the constant from (afair) cmath for it.