C++模块类基本用法为
template <class type>
class test
{
public:
test(type data);
private:
type data;
}
operator用于操作符重载
const test& operator=(const test&);
friend ostream& operator<<(ostream&, const test&);//此处为友原重载输出流
下面给出一个具体的代码实现
#include <map>
#include <utility>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
template <class Type1,class Type2>
class pair1
{
template<class Type1,class Type2>
friend ostream& operator<<(ostream& out,const pair1<Type1,Type2>& t);
public:
pair1()
{
}
pair1(Type1 data1, Type2 data2)
{
first_parameter = data1;
second_parameter = data2;
}
~pair1();
const pair1& operator=(const pair1<Type1,Type2>&);
private:
Type1 first_parameter;
Type2 second_parameter;
};
template<class Type1, class Type2>
pair1<Type1,Type2>::~pair1()
{
}
template<class Type1, class Type2>
const pair1<Type1,Type2> &pair1<Type1,Type2>::operator=(const pair1& t)
{
first_parameter = t.first_parameter;
second_parameter = t.second_parameter;
return *this;
}
template<class Type1, class Type2>
ostream& operator<<(ostream& out,const pair1<Type1,Type2>& t)
{
out << "(" << t.first_parameter << ", ";
out << t.second_parameter << ")" << endl;
return out;
}
int main()
{
pair1 <string,int> x ("num:",2);
pair1 <string,int> y;
pair1 <string,int> z("b",3);
y = z;
cout << x;
cout << y;
system("pause");
return 0;
}