模板笔记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);
}

-----------------------------------------------------------------------

posted @   MoonXu  阅读(159)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2019-03-30 gprof性能测试工具
点击右上角即可分享
微信分享提示