泛型编程初级操作 简单分数类 关于面向对象的一些基础知识。

#ifndef _SHARE_PTR_H_
#define _SHARE_PTR_H_

template <class T>
class Share_ptr
{
public:
T &operator *()const
{
return *px;
}
T *operator ->()const
{
return px;
}
Share_ptr(T *p):px(p){}
private:
T *px;
long *pn;
};

//类模板

// Complex<double>d | Complex<int>i
template<typename T>
class Complex
{
public:
Complex(T r = 0, T i = 0) :re(r), im(i) {}
T real()const { return re; }
T imag()const { return im; }
private:
T re;
T im;
};

//函数模板

template<typename T>
inline const T &min(const T&a, const T&b)
{
return a < b ? a : b;
}


//成员模板
template<class T1, class T2>
struct pair
{
typedef T1 first_type;
typedef T2 second_type;

T1 first;
T2 second;

pair() :first(T1()), second(T2()) {}
pair(const T1 &a, const T2 &b) :first(a), second(b) {}
template <class U1, class U2>
pair(const pair<U1, U2>&p) : first(p.first), second(p.second) {}

};

//模板特化
template<class Key>
struct hash
{

};
template<>
struct hash<char>
{

};
template<>
struct hash<int>
{

};
template<>
struct hash<long>
{

};


//模板偏特化和模板模板参数 后续需要补充。

#endif // !_SHARE_PTR_H_

// 面向对象 public private protect
/*-------------------------
父类类型
public private protect

继承方式 子类类型

public : public 不可见 protect

private: private 不可见 private

protect: protect 不可见 protect


-----------------------------*/

//虚函数 virtual 子类重新定义(override)
//纯需函数 virtual void draw()const=0;

//non-virtual 不希望重新定义

//构造函数调用顺序检查。


#include "pch.h"
#include"Share_ptr.h"
#include<bitset>
#include <iostream>
using namespace std;
//不完整的分数类
class Fraction
{
public:
Fraction(int num,int den=1):m_numerator(num),m_denominator(den){}
int m_num()const
{
return m_numerator;
}
int m_den()const
{
return m_denominator;
}
operator double() const
{
return (double)m_numerator / m_denominator;
}
Fraction operator+(const Fraction &f)
{
return Fraction(m_numerator, m_denominator);
}
private:
int m_numerator;
int m_denominator;
};
//重载<<
ostream &operator <<(ostream &os, const Fraction &f)
{
return os << f.m_num() << "\" << f.m_den();
}

//数量不定的模板参数 variadic template

void print(){}
template<typename T,typename...Types>
void print(const T &firstArg,const Types...args)
{
cout << firstArg << endl;
print(args...);
}

int main()
{
cout << __cplusplus << endl; //输出C++版本
Fraction F(3, 5);
double res = 4 + F;
cout << F<< endl;
cout << res << endl;

//variadic templates演示
print("Hello World", 16, bitset<16>(377), 7.77);

cout << "Hello World! ";
}

原文地址:https://www.cnblogs.com/yangshengjing/p/11631845.html