模板类的简单使用

#include <iostream>


using std::cout;
using std::cin;
using std::endl;


template<class T>
class Point
{
protected:
T x, y;
public:
Point(T x, T y)
{
this -> x = x;
this -> y = y;
}
virtual void show()
{
cout<< "Point:\n";
cout << "x =" << x << " " << "y =" << y <<endl;
}


};


template<class T>
class Rectangle : public Point<T>
{
private:
T h, w;
public:
Rectangle(T a, T b, T c, T d):Point<T>(a,b)
{
h = c;
w = d;
}
virtual void show()
{
cout << "Rectangle:\n";
cout << "x =" << x << " " << "y =" << y << " "<< "h =" << h << " "<< "w ="<< w << endl;
}


};


int main()
{
Point<int> a(3, 4);
Rectangle<float> b(5.1f, 6.2f, 7.3f, 8.4f);
a.show();
b.show();


Point<float> *p = &b;
p ->show ();


Rectangle<float> * pb = &b;
pb ->show();


return 0;

}


这个小程序是模板类的简单使用,模板类在编程实践中的用处还是十分大的。首先声明模板template <class T>或template<typename T> 第二 类名一定做相应的改变,加上<T>。

你可能感兴趣的:(C++,类,模板,虚函数)