C++ Programming Hi, I am having trouble calling on other functions in my print f
ID: 3793927 • Letter: C
Question
C++ Programming
Hi, I am having trouble calling on other functions in my print function. We must print a character and its position on a grid. I have
void Shape::print(void) const
{
int i = 0;
char name = name();
int n = size();
cout << name << " ";
while (i < n)
{
cout << "(" << x[n] << "," << y[n] << ") ";
i++;
}
}
The name and size function vary depending on the letter, but for the sake of testing it out we have:
int I::size(void) const
{
return 0;
}
char I::name(void) const
{
return 'I';
}
I think it has to do with how I am calling it. I am including below part of the .h file and the main file in case it is relevant. Any help is appreciated!! Thank you!
class Shape
{
public:
virtual ~Shape(void);
virtual char name(void) const = 0;
virtual int size(void) const = 0;
void print(void) const;
void move (int dx, int dy);
bool overlap(const Shape &t) const;
static Shape *makeShape(char ch,int posx,int posy);
protected:
int *x, *y;
};
//
// testShape.cpp
//
#include "Shape.h"
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
Shape *t1, *t2;
char ch;
int x,y;
try
{
cin >> ch >> x >> y;
t1 = Shape::makeShape(ch,x,y);
t1->print();
cin >> ch >> x >> y;
t2 = Shape::makeShape(ch,x,y);
t2->print();
t2->move(1,-1);
t2->print();
if ( t1->overlap(*t2) )
cout << "overlap" << endl;
else
cout << "no overlap" << endl;
delete t1;
delete t2;
}
catch ( invalid_argument &exc )
{
cout << exc.what() << ": " << ch << " " << x << " " << y << endl;
}
}
Explanation / Answer
#ifndef SHAPE
#include <iostream>
#include <stdexcept>
using namespace std;
class Shape
{
public:
virtual ~Shape(void);
virtual char sname(void) const = 0;
virtual int size(void) const = 0;
void print(void) const;
void move (int dx, int dy);
bool overlap(const Shape &t) const;
static Shape *makeShape(char ch,int posx,int posy);
protected:
int *x, *y;
};
#define SHAPE
#endif
void Shape::print(void) const
{
int i = 0;
char name = sname();
int n = size();
cout << name << " ";
while (i < n)
{
cout << "(" << x[n] << "," << y[n] << ") ";
i++;
}
}
int i::size(void)
{
return 0;
}
char i::sname(void)
{
return 'i';
}
int main()
{
Shape *t1, *t2;
char ch;
int x,y;
try
{
cin >> ch >> x >> y;
t1 = Shape::makeShape(ch,x,y);
t1->print();
cin >> ch >> x >> y;
t2 = Shape::makeShape(ch,x,y);
t2->print();
t2->move(1,-1);
t2->print();
if ( t1->overlap(*t2) )
cout << "overlap" << endl;
else
cout << "no overlap" << endl;
delete t1;
delete t2;
}
catch ( invalid_argument &exc )
{
cout << exc.what() << ": " << ch << " " << x << " " << y << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.