Hello.
The code I'm trying to do,
class Shape {
protected:
int type; // POINT, CIRCLE, RECTANGLE, or TRIANGLE
public:
virtual double area()=0;
virtual bool isContaining(const Point&)=0;
enum {POINT, CIRCLE, RECTANGLE, TRIANGLE};
friend bool operator==(const Shape&, const Shape&);
};
class Rectangle : public Shape {
Point rightUpper, leftLower;
public:
Rectangle(const Point&, const Point&);
bool isContaining(const Point&);
…
}
class Circle : public Shape {
Point Center;
double radius;
public:
Circle(const Point&, double);
bool isContaining(const Point&);
…
};
class Triangle : public Shape {
Point p1, p2, p3;
public:
Triangle(const Point&, const Point&, const Point&);
bool isContaining(const Point&);
…
};
In this way, the Point, Rectangle, Circle, Triangle classes that inherit Shape, and
class ShapeSet {
Shape** shapes;
int numShapes;
int maxShapes;
public:
...
};
It's a class called ShapeSet that contains these shapes.
The thing that got stuck while coding is, in class shape,
friend bool operator==(const Shape&, const Shape&);
Part. To determine if two shapes are the same or different,
It's not the member data type of Shape If it's Point, compare the member data x and y, If it's Rectangle, compare the member data rightUpper and leftLower Rectangle Circle Point Triangle should all be implemented in different ways
With operator== parameter types set to Shape, Can't you compare Triangle and Triangle, Rectangle and Rectangle?
When using derivative classes as parameters, the base class can come, I've learned that the other way aroundㅠ<
c++ overriding polymorphism
There are many ways. The simplest is to create a virtual method that returns only names.
For example, create a virtual method name() as follows:
When you override ==
, you can make a comparison of name().
#include<iostream>
using namespace std;
class Base{
public:
virtual string name() const = 0; // virtual method that returns the name
};
class Sub1 : public Base{
public:
string name() const {
return "Sub1";
}
};
class Sub2 : public Base{
public:
string name() const {
return "Sub2";
}
};
int main(){
Sub1* sub1 = new Sub1();
Sub2* sub2 = new Sub2();
Base* base1 = sub1;
Base* base2 = sub2;
cout << base1->name() << endl; // output "Sub1"
cout << base2->name() << endl; // output "Sub2"
}
Output result:
Sub1
Sub2
© 2024 OneMinuteCode. All rights reserved.