模板笔记9 静多态和动多态
1. 继承是动多态
2.模板是静多态(ploy.cpp ploy .hpp)
--------------------------------------------------------------
ploy.hpp
#include <cstdlib>
#include <vector>
#include <iostream>
class Coord {
private:
int x, y;
public:
Coord (int i1, int i2) : x(i1), y(i2) {}
friend Coord operator- (Coord const& c1, Coord const& c2) {
return Coord(c1.x-c2.x, c1.y-c2.y);
}
Coord abs() {
return Coord(std::abs(x), std::abs(y));
}
void print()
{
std::cout << "x: " << x << " y: " << y << std::endl;
}
};
class Circle {
public:
Circle(int a, int b): x(a), y(b){}
void draw() const;
Coord center_of_gravity()const;
private:
int x, y;
};
class Line {
public:
Line(int a1, int b1, int a2, int b2):x1(a1),x2(a2), y1(b1), y2(b2){}
void draw() const;
Coord center_of_gravity()const;
private:
int x1, x2, y1, y2;
};
void Circle::draw() const
{
std::cout << "Circle" << std::endl;
}
Coord Circle::center_of_gravity()const
{
return Coord(x, y);
}
void Line::draw() const
{
std::cout << "Line" << std::endl;
}
Coord Line::center_of_gravity() const
{
return Coord((x1 + x2) / 2, (y1 + y2) /2);
}
-------------------------------------------------------------------------
ploy.cpp
#include "ploy.hpp"
template<typename GeoObj>
void myDraw (GeoObj const& obj)
{
obj.draw();
}
template<typename GeoObj1, typename GeoObj2>
Coord distance (GeoObj1 const& m1, GeoObj2 const& m2)
{
Coord c = m1.center_of_gravity() - m2.center_of_gravity();
c.print();
return c;
}
template<typename GeoObj>
void drawElems (std::vector<GeoObj> const& elems)
{
for(unsigned i = 0; i<elems.size(); ++i)
{
elems[i].draw();
}
}
int main()
{
Line l(4, 4, 5, 5);
Circle c(1, 1), c1(2, 2), c2(3, 3);
myDraw(l);
myDraw(c);
distance(c1, c2);
distance(l, c);
std::vector<Line> coll;
coll.push_back(l);
drawElems(coll);
}
-----------------------------------------------------------------------