STL学习

打印 上一主题 下一主题

主题 838|帖子 838|积分 2514

手写STL源码

模板
  1. //TemplateDemo
  2. #include<iostream>
  3. using namespace std;
  4. //交换两个变量
  5. void MySwap(int& a, int& b)
  6. {
  7.         int temp = a;
  8.         a = b;
  9.         b = temp;
  10. }
  11. //使用模板--自适应类型生成函数,地址不同
  12. //函数重载和模板函数冲突,优先调用普通函数,或者使用<T>()显示调用
  13. //不支持隐式转换
  14. template<typename T>
  15. void MyTSwap(T& a, T& b)
  16. {
  17.         int temp = a;
  18.         a = b;
  19.         b = temp;
  20. }
  21. int main()
  22. {
  23.         int a = 10;
  24.         int b = 20;
  25.         MyTSwap(a, b);
  26.         MyPrint(a, b);
  27. }
复制代码
操纵符重载

[code]class Complex{public:        double real;        double image;        Complex(double real, double image) :real(real), image(image) {}        Complex Add(Complex& other)        {                return Complex(this->real + other.real, this->image + other.real);        }        Complex Mulitply(Complex& other)        {                double a = this->real;                double b = this->image;                double c = other.real;                double d = other.image;                return Complex(a * c - b * d, b * c + a * d);        }        Complex operator+(Complex& other)        {                return Complex(this->real + other.real, this->image + other.real);        }        Complex operator*(Complex& other)        {                double a = this->real;                double b = this->image;                double c = other.real;                double d = other.image;                return Complex(a * c - b * d, b * c + a * d);        }};ostream& operator
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

前进之路

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表