【c++系列14】让数据类型成为对象

本文使用模板类让数据类型成为对象。主要实现了Integer和Double,操作主要实现了<<和+以及+=,其他类型或者操作感兴趣的可以自己尝试。


#include <iostream>

using namespace std;

template <typename T> class Object;

// function template declaration must precede friend declaration in Object
template <typename T> ostream& operator<<(ostream&, const Object<T>&);

template <typename T> class Object{
	T data;
public:
	Object(T data){this->data=data;}
	Object<T>(const Object<T> &o){this->data = o.data;}
	Object& operator+=(const Object &b){data+=b.data;return *this;}

	friend ostream& operator<< <T>(ostream&, const Object<T>&);
	
	void show(){cout<<data<<endl;};
};

template <typename T> Object<T> operator+(const Object<T> &a,const Object<T> &b){
	Object<T> result(a);
	result += b;
	return result;
}

template <typename T> ostream& operator<<(ostream& out, const Object<T>& a){
	return out<<a.data;
}

class Integer:public Object<int>{
public:
	Integer(int i):Object(i){};
};

class Double:public Object<double>{
public:
	Double(double d):Object(d){};
};

int main(int argc, char const *argv[])
{
	Integer i(10);
	cout<<i<<" "<<Integer(3)+Integer(5)<<endl;

	Double d1(10.2);
	Double d2(10.3);
	(d1+d2).show();
	cout<<d1+d2<<endl;
	return 0;
}


你可能感兴趣的:(C++)