I have an assignment where I am supposed to draw a rectangle shape, the way is to specify two points in a plane, draw two horizontal and two vertical lines. We are supposed to use the Point class in the Rectangle class.
I have the assignment instructions .h (point class), .cpp (Point class), .h (Rectangle class), .cpp (Rectange class) and the main. I didn't do too much in main but specified what should be done. He wants a rectangle drawn with the outline consisting of the y's or the character y.
I think everything is good in the .h (point class), .cpp (Point class), .h (Rectangle class), but I am having issues with the draw method and print method of the Rectangle .cpp, the instructor said to just use a temp variable for the origin in the draw method or something like that,
Also not sure about the print method in the .cpp Rectangle file, would appreciate help here. Tried to compile but all hell broke loose, any explanation/example would help a lot.
Point.h
//Point.h
#include <iostream.h>
/* The Point class Header file (Point.h) */
#ifndef POINT_H
#define POINT_H
class Point {
private:
double x,y;//x and y are private variables
public:
Point(int x, int y):x(x),y(y){}//use initialization list
double getX() const; //Getters
double getY() const;
void setX(double x); //Setters
void setY(double y); //Setters
void print()const;
//Overload '+' operator
const Point operator +(const Point & rt)const;
//Overload '-' operator
const Point operator - (const Point &rt)const;
Point operator +=(Point & rt);
Point operator -=(Point & rt);
//Overload '==' operator comparing two points
int operator ==(Point &rt);
int operator <(Point &rt);
int operator >(Point &rt);
int operator <=(Point &rt);
int operator >=(Point &rt);
};
/* POINT_H */
#endif
Point .cpp
//the Point.cpp file
#include "Point.h"
#include<iostream>
using namespace std;
//Getters
double Point::getX()const {return x;}
double Point::getY()const {return y;}
//setters
void Point::setX(double x) {this->x=x;}
void Point::setY(double y) {this->y=y;}
//Public functions
void Point::print()const{
cout << "(" << x << "," << y << ")" << endl;
}
//overloading '+' operator
const Point Point::operator+(const Point & rt) const{
return Point(x + rt.x, y + rt.y);
}
const Point Point::operator-(const Point & rt) const{
return Point(x - rt.x, y - rt.y);
}
Point Point::operator+=(Point & rt){
return Point(x+=rt.x, y+=rt.y);
}
int Point::operator ==(Point & rt){
return (x == rt.x && y==rt.y);
}
int Point::operator <(Point & rt){
return (x < rt.x && y<rt.y);
}
int Point::operator >(Point & rt){
return (x > rt.x && y>rt.y);
}
int Point::operator <=(Point & rt){
return (x <= rt.x && y<=rt.y);
}
int Point::operator >=(Point & rt){
return (x >= rt.x && y>=rt.y);
}
//;
//;
//END POINT.CPP
Rectangle h file
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <iostream.h>
#include "Point.h"
class Rectangle {
private:
Point origin;
Point corner;
public:
Rectangle (const Point & or, const Point & cr):origin(or),corner(cr) {}
// void move(int dx, int dy);
void draw();
void print()const;
};
#endif /* RECTANGLE_H */
Rectangle .cpp file
/* The Rectangle.cpp file) */
#include "Point.h"
#include "Rectangle.h"
#include <iostream.h>
#include <string>
#include <conio.h>
using namespace std;
// Public Functions
void Rectangle::print() const
{
cout<<"(" <<origin <<"," <<corner << ")" <<endl;
}
void Rectangle::draw()
{
Point temp=origin; //store origin in temp object
while (temp.getX() < corner.getX()) {
putch('y');
}
/* int temp=origin;
for (int x = temp.getX(); x < center.getX(); x++) {
Point pt1 (x, temp.getY());
Point pt2 (x, center.getY());
pt1(6,4);
// move to p1 // not sure how to do this
putCH ('y');
pt2(30,15);
// move to p2 //not sure how to do this
putCH ('y');
}
for (int y = lowerRight.getY(); y < upperLeft.getY(); y++) {
Point pt1 (origin.getX(),y);
Point pt2 (corner.getX(),y);
pt1(6,4);
//move to p1 //not sure how to do this
putCH('y');
pt2(30,15);
// move to p2 //not sure how to do this
putCH ('y');
}*/
//return 0;
}//;
MAIN
#include "Point.h"
#include "Rectangle.h"
#include <iostream>
#include <conio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//char y;
Point p1(6, 4), p2(30, 15);
//cout<<"\n the origin of Rectangle is at: ";
//p1.print();
//cout<<"\n the opposite corner of rect is at:";
//p2.print();
Rectangle r1(p1,p2);
r1.draw();
clrscr();
gotoxy(1,20);
//r1.print();
getch();
return 0;
} //;
//END OF MAIN
I could see one C++ specific issue: you did not overload "<<" operator on Point. First please do that.
Secondly, which compiler are you using?
clrscr(); gotoxy();
are not part of standard C+++.
If your compiler supports them, well and good.
Otherwise, you need to look for alternatives.
Good convention: avoid
using namespace std;
Instead, write
std::cout
std::endl;
etc
I did not go through your actual logic.
Which is actually your assignment - isnt't it?
Related
Vector2D hpp files
#ifndef Vector2D_hpp
#define Vector2D_hpp
#include <iostream>
#include "Point2D.hpp"
namespace GeoBox{
class Vector2D{
Point2D m_point1{};
Point2D m_point2{};
public:
Vector2D() = default;
Vector2D(Point2D &point1, Point2D &point2)
{
m_point1 = point1;
m_point2 = point2;
}
void setVector(Point2D &point1, Point2D &point2);
};
Vector2D.cpp files
#include "Vector2D.hpp"
#include "Point2D.hpp"
void GeoBox::Vector2D::setVector(GeoBox::Point2D &point1, GeoBox::Point2D &point2) {
Vector2D(point1, point2);
}
main.cpp
int main(int argc, const char * argv[]) {
GeoBox::Point2D point1{3.0, 1.0};
GeoBox::Point2D point2{2.0, 3.0};
GeoBox::Vector2D vect1{point1, point2};
}
I am trying to create a vector consisting of 2 points. how can i create their getters and settlers? I think I created the setter function, but I'm not sure.
note:GeoBox my file name
To create a vector, you should initialize it as a template type.
For the setter function you must implement the erase () function that can receive two iterators, one that points to the value you want to delete or two iterators if you want to delete an element range pointing to the initial and last value.
The erase () function is already a function implemented in c ++ 11 but it can be developed.
Its seems like this might work. I changed your class to store pointers and not objects for efficiency. Granted, I can't test that this because I don't have the rest of your code and can't guarantee your setup.
#ifndef Vector2D_hpp
#define Vector2D_hpp
#include <iostream>
#include "Point2D.hpp"
namespace GeoBox {
class Vector2D {
Point2D* points[2];
public:
Vector2D() = default;
Vector2D(Point2D* point1, Point2D* point2)
{
setVector(point1, point2);
}
void setVector(Point2D* point1, Point2D* point2) {
points[0] = point1;
points[1] = point2;
}
Point2D* getVector() {
return points;
}
};
}
#endif
To do this with a struct (and without pointers in this case) you would set it up like this:
#ifndef Vector2D_hpp
#define Vector2D_hpp
#include <iostream>
#include "Point2D.hpp"
namespace GeoBox {
class Vector2D {
struct Vector { //Define the struct
Point2D point1;
Point2D point2;
} points; //Create instance of struct
public:
Vector2D() = default;
Vector2D(Point2D point1, Point2D point2)
{
setVector(point1, point2);
}
void setVector(Point2D i_point1, Point2D i_point2) {
points.point1 = i_point1; //Access struct components
points.point2 = i_point2;
}
Vector getVector() {
return points; //return struct
}
};
}
#endif
Pointers can (and should) still be used in this case however as they allow for increased speed in your program overall.
I am learning c++ and getting the compilation error while doing operator overloading. I am attaching my code. Please have a look. The error is at line no 27.
I tried to make changes but as I am totally new to c++, I am unable to resolve this. We don't have anything like this in C.
Also, suggest me some good way to improve my coding standard and skills.
#include <iostream>
#include<string>
#include <string.h>
#include <stdlib.h>
using namespace std;
class rectangle
{
private:
int l,b;
public:
// friend
rectangle(int,int);
rectangle(rectangle &r);
void setL(int);
void setB(int);
int getL();
int getB();
int area();
int parameter();
void isSquare();
rectangle operator + (rectangle r1)
{
rectangle temp; // compilation error here ///////Line No 27:
temp.l=r1.l+l;
temp.b=r1.b+b;
return temp;
}
// void ~rectangle();
};
void rectangle:: isSquare()
{
if(l==b)
cout<<"It is square"<<endl;
else
cout<<"It is rectangle"<<endl;
}
rectangle:: rectangle(int length =0, int breadth =0)
{
setL(length);
setB(breadth);
}
rectangle:: rectangle(rectangle &r)
{
setL(r.l);
setB(r.b);
}
void rectangle::setL(int length)
{
if(length>0)
l=length;
else
l=0;
}
void rectangle::setB(int breadth)
{
if(breadth>0)
b=breadth;
else
b=0;
}
int rectangle::getL()
{
return l;
}
int rectangle::getB()
{
return b;
}
int rectangle::area()
{
return l*b;
}
int rectangle::parameter()
{
return 2*l*b;
}
//extern void print(char *s);
int main()
{
cout<<("Welcome to test codes!!! :) :) \n");
rectangle r(10,5);
rectangle r1(2,5);
rectangle r2;
cout<<"r "<<r.area()<<' '<<r.parameter()<<endl;
cout<<"r1 "<<r1.area()<<' '<<r1.parameter()<<endl;
cout<<"r2 "<<r2.area()<<' '<<r2.parameter()<<endl;
r.isSquare();
r2=r+r1;
cout<<"r2 "<<r2.area()<<' '<<r2.parameter()<<endl;
return 0;
}
Error is main.cpp:32:19: error: no matching function for call to 'rectangle::rectangle()'
rectangle temp;
Look at your constructors
rectangle(int,int);
rectangle(rectangle &r);
One that takes two integers, and one that takes another rectangle. So this means to construct a rectangle you must provide either two integers or another rectangle.
Now look at the line with the error
rectangle temp;
What's provided here? Nothing of course, but you don't have a constructor with no arguments, so this is a compilation error.
Looking at your code the best solution is this
rectangle temp(r1.l+l, r1.b+b);
return temp;
Now two integers are being provided.
BTW your code shows a complete lack of awareness of const. You're going to quickly run into trouble unless you learn about that.
The line
rectangle temp; // compilation error here ///////
is trying to create a new instance of "rectangle" without any constructor parameters. Your class does not have a constructor that takes no parameters, that's why you get the error. It has nothing to do with your operator.
You need to use:
rectangle temp(0, 0);
Or, create a constructor that takes no parameters:
in header
rectangle();
in source file
rectangle:: rectangle() {}
I have this homework assignment to do and I did most of the code, but I have a remaining compiling error in main(), that I do not understand.
Here's the assignment:
Define an abstract base class called BasicShape. The BasicShape class should have the following members (...)
Define a class named Circle. It should be derived from the BasicShape class.
It should have the following members:
a) Private Member Variable: radius (a double used to hold the circle’s
radius)
b) Constructor and Public Member Functions:
Circle(double a, string
n, double r): constructor that should call the base class constructor
to initialize the member area with a and name with n. The constructor
will also set the value of member radius with r
calcArea():
Overridden function (...)
print(): Overridden function (...)
After you have created these classes, create a test program
(...)
And here's my code:
Basic Shape.h
#ifndef BASICSHAPE_H
#define BASICSHAPE_H
#include <string>
class basicShape
{
public:
basicShape(const std::string &, double &);
double getArea() const;
virtual double calcArea() const = 0;
virtual void print()const;
std::string getname()const;
protected:
const double area;
private:
const std::string name;
};
#endif
Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include <string>
#include "Basic Shape.h"
using namespace std;
class Circle : public basicShape
{
public:
Circle(const string & n, double & a, double & r);
virtual double calcArea() const override;
virtual void print() const override;
private:
double radius;
};
#endif
Circle.cpp
#include <iostream>
#include "Circle.h"
#include<string>
using namespace std;
Circle::Circle(const string &n, double &a, double &r)
:basicShape(n,a)
{
radius = r;
calcArea();
}
double Circle::calcArea() const
{
double area;
area = 3.14159*radius*radius;
return area;
}
double basicShape::getArea() const
{
return area;
}
void Circle::print() const
{
cout << "radius:" << radius;
basicShape::print();
basicShape::getname();
}
Test.cpp
#include <iostream>
#include "Basic Shape.h"
#include "Circle.h"
#include <string>
#include<vector>
using namespace std;
void poly(const basicShape * const);
int main()
{
Circle circle("Round",0.0,10.0);
vector< basicShape * > shapes(1);
for (const basicShape *basicshapePtr : shapes)
poly(basicshapePtr);
}
void poly(const basicShape * const baseClassPtr)
{
baseClassPtr->calcArea();
baseClassPtr->print();
}
Here is the compiling error I get in main:
"Circle::Circle(Circle Assignment 3 &&)': cannot convert argument 2 from 'double' to 'double &'
The problem
You try to construct your new circle here:
Circle circle("Round",0.0,10.0);
But your constructor has the following signature:
Circle(const string &n, double &a, double &r)
For the second and third arguments you use references to double values. Passing by reference like this means that you could change the value that is referenced. Unfortunately, you pass constant literals. This is not allowed.
The solution
Either define your constructor by using const references:
Circle(const string &n, const double &a, const double &r)
or, pass by value:
Circle(string n, double a, double r)
Note that the second option seems preferred here. And I'd even advise you to respect the signature given in the assignment, which would have avoided you those troubles.
P.S.: For future questions, please reduce the question to the minimal elements required to reproduce the errors, instead of posting the full assignment and the full code, most of which being not relevant to the error
I am new to operation overloading. I doing a lab where I need to be able to show the Area and circumference of a circle. The user inputs the radius and the center x,y point. My problem is that I am lost in how to properly execute the operation overload on multiplication. Could some one please help me?
This is the portion of the main.cpp
cout << "====================================================" << endl;
cout << "Radius is: " << circle1.setRadius << endl;
cout << "Area is: " << circle1.setArea << endl;
cout << "Circumference is: " << circle1.setCircumference << endl;
This is my circleTypeImp.cpp
#include <iostream>
#include "circleType.h"
#include "pointType.h"
class CircleType;
const float PI = 3.14;
void CircleType::setRadius (float r)
{
float radius const=r;
}
void CircleType::printCircle() const
{
}
void CircleType::setArea ()
{
return PI * radius * radius;
}
void CircleType::setCircumference ()
{
return 2 * PI * radius;
}
and this is my CircleType.h
#ifndef CIRCLETYPE_H
#define CIRCLETYPE_H
#include "pointType.h"
#include <iostream>
using namespace std;
class CircleType : public PointType
{
public:
void setRadius(float r);
void printCircle() const;
CircleType& operator* (const CircleType& radius);
void setArea();
void setCircumference();
private:
float radius const;
};
#endif
Thank you
Here's what I could come up with to help you out, based on your clarifications.
I've pasted and edited the code you had, and added comments to it when I made changes to detail why those changes where made.
A few of the highlights:
When calling any function, even those without parameters, you still need the ().
Functions that return a value, should not return void but rather the type of the return value. (i.e. float in the cases below).
When you want to set a member variable it's customary to use setVariableName or something similar and when you're returning the value of a member variable (or simple operation on) you can use getVariableName
so as to avoid confusion over what the function should do.
You should avoid using namespace std in header files (.h/.hpp files), so as not to force everyone using your code to also use the same namespaces.
radius shouldn't be declared const as you want to be able to set it's value after creating the object.
when using PI you often want the most accurate representation for your variable type. You can often find this on many systems in cmath as M_PI (#include <cmath>).
I haven't done really anything with the PointType class or the overloaded multiplication operator as 1. I have no clue what the PointType class looks like and the multiplication operator doesn't seem necessary.
Below is a sample program using this class to illustrate how to use the member functions.
CircleType.h
#ifndef CIRCLE_TYPE_H
#define CIRCLE_TYPE_H
#include "PointType.h"
#include <iostream>
// It's common practice to not put "using namespace" in a header file.
// If you do, anyone including your header file has to use it.
class CircleType : PointType {
public:
void setRadius(const float r);
void printCircle() const;
CircleType operator * (const circleType& c) const;
float getRadius() const;
float getArea() const;
float getCircumference() const;
private:
float radius; // Note because you want to set radius
// after creation of a circle object
// radius should not be const
}
#endif
CircleType.cc
#include "CircleType.h" // PointType.h will also be included
#include "PointType.h" // But it's also fine to explicitly include it
#include <iostream>
using namespace std;
// you don't need a dummy class here, In fact that will likely cause a compiler issue
// You should probably use a more accurate value of Pi
const float PI = 3.1415927; // Or use M_PI in "cmath" (if it's defined on your system)
void CircleType::setRadius(const float r){
radius = r;
}
void CircleType::printCircle() const {
// Do whatever you need to print a circle
}
// As far as I can tell, you don't actually need to overload
// multiplication to do any the tasks you mentioned.
CircleType CircleType::operator * (const CircleType& c) const {
CircleType tmp;
// I have no clue what multiplying two circles gives you,
// this is the general form of the multiplication operator
return tmp;
}
// It is customary to name a function that returns a private variable
// or the result of simpler operations on private variables with getXXX
// like the ones below -- Note the return type is not void but
// the actual type you expect.
float CircleType::getRadius() const {
return radius;
}
float CircleType::getArea() const {
return PI * radius * radius;
}
float CircleType::getCircumference() const {
return 2 * PI * radius;
}
main.cc
#include "CircleType.h"
#include "PointType.h"
#include <iostream>
using namespace std;
int main(int argc, char ** argv){
CircleType c1;
float tmp;
cout << "Input radius of circle: ";
cin >> tmp;
c1.setRadius(tmp);
cout << "=============================================" << endl;
// note even for functions that take no parameters, you still need the () to call it
cout << "Radius is: " << c1.getRadius() << endl;
cout << "Area is: " << c1.getArea() << endl;
cout << "Circumference is: " << c1.getCircumference() << endl;
return 0;
}
Intro:
In my program, a group object has an std::vector full of polygons (a ring and holes) and a polygon object has an std::vector of points. In reality, the classes are more complicated, I've stripped them down here to illustrate my problem.
The problem:
I want to be able to modify the point's x and y coordinates from within it's corresponding group object. Below, in group.cpp, I have a dummy function called void Group::tryChangingAllX() that tries to accomplish this. However, calling show() on the group afterwards shows no change to it's polygon's point's coordinates.
I think I need to use references/pointers, but I need a nudge in the right direction.
point.cpp:
#include "point.h"
#include <iostream>
Point::~Point(){}
Point::Point(int x, int y){
_x = x;
_y = y;
}
void Point::show(){std::cout << "(" << x() << "," << y() << ")";}
void Point::x(int x){_x = x;}
void Point::y(int y){_y = y;}
int Point::x(){return _x;}
int Point::y(){return _y;}
point.h:
#ifndef POINT_GUARD
#define POINT_GUARD
class Point{
int _x;
int _y;
public:
Point(int x, int y);
~Point();
void show();
int x();
int y();
void x(int x);
void y(int y);
};
#endif
polygon.cpp:
#include "polygon.h"
#include "point.h"
#include <iostream>
#include <vector>
Polygon::~Polygon(){}
Polygon::Polygon(){}
std::vector<Point> Polygon::points(){return _points;}
Polygon::Polygon(std::vector<Point> points){_points = points;}
void Polygon::show(){
std::cout << "Points: ";
for(std::vector<Point>::size_type i = 0; i != _points.size(); i++) {
_points[i].show();
}
}
polygon.h:
#ifndef POLYGON_GUARD
#define POLYGON_GUARD
#include <vector>
#include "point.h"
class Polygon{
//private:
std::vector<Point> _points;
public:
~Polygon();
Polygon ();
Polygon(std::vector<Point> points);
std::vector<Point> points();
void show();
};
#endif
group.cpp:
#include <iostream>
#include <vector>
#include "group.h"
#include "polygon.h"
Group::~Group(){}
Group::Group(std::vector<Polygon> polygons){
_ring = polygons.front();
polygons.erase(polygons.begin());
_holes = polygons;
}
void Group::tryChangingAllX(){
std::vector<Point> points = _ring.points();
for(std::vector<Point>::size_type i = 0; i != points.size(); i++) {
points[i].x(15);
}
}
void Group::show(){
_ring.show();
if(_holes.size()>0){
for(std::vector<Polygon>::size_type i = 0; i != _holes.size(); i++) {
_holes[i].show();
}
}
}
group.h:
#ifndef GROUP_GUARD
#define GROUP_GUARD
#include <vector>
#include "polygon.h"
class Group{
Polygon _ring;
std::vector<Polygon> _holes;
public:
~Group();
Group(std::vector<Polygon> polygons);
void show();
void tryChangingAllX();
};
#endif
Thanks!
The function
std::vector<Point> points();
returns by value, so when you call it, you get a copy of the member. You need to change it to
std::vector<Point>& points();
After you've done this
std::vector<Point> points = _ring.points();
also makes a copy of the returned value. To refer to the actual member in _ring, change to:
std::vector<Point>& points = _ring.points();
That should do it.
Note that you should pass std::vector by const reference to prevent an un-necessary copy:
Polygon(const std::vector<Point>& points);
and consider making methods that don't modify the class const:
int x() const;
This is exactly your problem - you're getting a copy of your points rather than working on a reference to the original points themselves.
polygon.cpp:
return points by reference not value:
std::vector<Point>& Polygon::points(){return _points;} // note the '&' in the return
group.cpp:
obtain a reference to the points, not a copy
std::vector<Point>& points = _ring.points(); // note the '&' in what you're getting
Answers posted by Luchian and lori are technically correct. But there are design considerations that I want to point out.
Returning a reference will allow anyone to modify private parts of Polygon object. By design you only want Group class to do this. Consider making Group a friend of Polygon. Group then will have access to private bits of Polygon. This will ensure a tighter encapsulation overall.
In polygon.h
friend class Group;
In group.cpp
void Group::tryChangingAllX()
{
for(std::vector<Point>::size_type i = 0; i != _ring._points.size(); i++)
{
_ring._points[i].x(15);
}
}