您的位置:首页 > 编程语言 > C语言/C++

学习C++ 模板类

2015-06-25 16:31 411 查看
#include<iostream>
#include<typeinfo>
#include<cstring>

using namespace std;

class A
{
public:
A(int x, int y) :m_x(x), m_y(y)
{

}

int compare(void)
{
cout << "Type of m_x is" << typeid (m_x).name() << endl;
cout << "Type of m_y is" << typeid (m_y).name() << endl;

if (m_x < m_y)
return -1;
if (m_x > m_y)
return 1;

return 0;

}
private:
int m_x;
int m_y;

};

class B
{
public:
B(double x, double y) :m_x(x), m_y(y)
{
}
int compare(void)
{
cout << "Type of m_x is" << typeid (m_x).name() << endl;
cout << "Type of m_y is" << typeid (m_y).name() << endl;

if (m_x < m_y)
return -1;
if (m_x > m_y)
return 1;

return 0;

}
private:
double m_x;
double m_y;

};

class C
{
public:
C(string x, string y) :m_x(x), m_y(y)
{

}

int compare(void)
{
cout << "Type of m_x is" << typeid (m_x).name() << endl;
cout << "Type of m_y is" << typeid (m_y).name() << endl;

if (m_x < m_y)
return -1;
if (m_x > m_y)
return 1;

return 0;

}
private:
string m_x;
string m_y;

};

template < class T> class D
{
public:
D(T x, T y) : m_x(x), m_y(y)
{
}

int compare(void)
{
cout << "Type of m_x is" << typeid (m_x).name() << endl;
cout << "Type of m_y is" << typeid (m_y).name() << endl;

if (m_x < m_y)
return -1;
if (m_x > m_y)
return 1;
}
private:
T m_x;
T m_y;
};

int main(int agrc, char* argv[])
{
// 不用模板
int r;
A a(10, 20);
cout << "A:: Compare() return " << a.compare() << endl;

B b(0.1, 0.2);
cout << "B:: Compare() return " << b.compare() << endl;

C c("pan", "tan");
cout << "C:: Compare() return " << c.compare() << endl;

cout << "====================================" << endl;
//用模板类

D<int> d1(10, 20);
cout << "A:: Compare() return use panel " << d1.compare() << endl;

D <double> d2(0.1, 0.3);
cout << "B:: Compare() return use panel" << d2.compare() << endl;

cin >> r;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: