blob: 99edd5256e11c387ef20cf088e27c68e65e49ffb (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#include <iostream>
#include <string>
/* below tweak needs to know wbout this class */
template <class T>
class Polygon;
/* convine the compiler that overloaded operators are templates themselves before
* we reach the declaration of the class */
template <class T>
std::ostream& operator<<(std::ostream &, const Polygon<T> &);
template <class T>
class Polygon
{
public:
/* notice the <> after function name, we're letting g++ know this is a template */
friend std::ostream& operator<<<>(std::ostream &, const Polygon<T> &);
/* pure virtual, subclass must DEFINE it. otherwise that subclass itself
* will remain abstract and won't be able to be instantiated */
virtual T area(void) = 0;
T getWidth(void) {
this->width;
}
T getHeight(void) {
this->height;
}
protected:
T width, height;
std::string type; /* name of polygon */
};
template <class T>
class Triangle : public Polygon<T>
{
public:
Triangle() {
this->width = 0;
this->height = 0;
this->type = std::string("triangle");
}
Triangle(int b, int h) {
this->width = b;
this->height = h; /* this keyword has to be used? */
this->type = std::string("triangle");
}
virtual T area(void) {
return (this->width * this->height) / 2;
}
};
template <class T>
std::ostream& operator<<(std::ostream& stream, const Polygon<T>& p)
{
stream << p.type << " dimensions, width: " << p.width << ", height: " << p.height
<< ", area: "<< const_cast<Polygon<T> *>(&p)->area(); /* lol at the cast! */
return stream;
}
int main(int argc, char *argv[])
{
Triangle<int> tri(6, 4);
std::cout << tri << std::endl;
return 0;
}
|