zoukankan      html  css  js  c++  java
  • *** 类模板sample code

    #include <iostream>
    using namespace std;
    
    template <class T1, class T2>
    class Point
    {
    public:
        Point(T1 x=0, T2 y=0):a(x), b(y){}
        Point(const Point<T1,T2> & x)
        {
            a = x.a;
            b = x.b;
        }
        ~Point(){}
        
        Point<T1,T2> & operator= (const Point<T1,T2> & x)
        {
            a = x.a;
            b = x.b;
            return *this;
        }
        
        Point<T1,T2> operator+ (const Point<T1,T2> & x) //注意返回值不是引用而是值传递
        {
            Point<T1,T2> temp;
            temp.a = a + x.a;
            temp.b = b + x.b;
            return temp;
        }
    
        T1 a;
        T2 b;
    };
    
    template <class T1, class T2>
    ostream & operator<< (ostream & out, Point<T1,T2> &x)
    {
        out << "(" <<x.a << ", " << x.b << ") " << endl;
        return out;
    }
        
    int main()
    {
        Point<int, double> a1(3, 2.4);
        Point<int,double> b1(2, 1.1);
        Point<int, double> c1;
    
        c1 = a1 + b1;
        cout << a1 << b1 << c1 << endl;
        
        Point<double, float> a2(1.11, 5.43);
        Point<double, float> b2(11.7,9.2);
        Point<double, float> c2 = a2 + b2;
        
        cout << a2 << b2 << c2 << endl;
        
        return 0;
    }

     下面代码展示通过继承方式把模板中与参数无关的代码分离出来

    #include <iostream>
    using namespace std;
    
    template<class T>
    class Base
    {
    public:
        Base(T x):value(x){}
        virtual void print(void)
        {
            cout << "Base::value = " << value << endl;
        }
    
        T value;
        int k=0;
    };
    
    template<class T, T num>
    class Derived: public Base<T>
    {
    public:
        Derived():Base<T>(num){}
        virtual void print(void)
        {
            cout << "Derived::k = " << this->k << endl;
        }
    };
    
    int main()
    {
        Derived<int, 1> a;
        Derived<int, 2> b;
        Derived<int, 3> c;
        a.print();
        b.print();
        c.print();
        
        return 0;
    }
  • 相关阅读:
    关于Update语句在不同数据库中的差别
    MSIL指令速查表
    一个对于博客园的建议
    代码风格关于if语句
    关于Page.cs文件中注释的一点补充
    在Java、C#和C++中遍历集合
    BPEL4WS的开源Java实现
    【Linux】linux固定ip
    【Linux】【MySQL】MySQL主从数据库
    wpf 写个简单的控件吧
  • 原文地址:https://www.cnblogs.com/superrunner/p/10163576.html
Copyright © 2011-2022 走看看