c++模板类的简单使用

因为这几天在重学c++,说来也是惭愧,以前学习的时候一般学到多态那里就结束了,后面的模板类和stl都没有看过

终于下定决心看了看,发现模板类很方便,上demo

#include<iostream>
using namespace std;

struct Point {
  int x, y;
  Point(int x=0, int y=0):x(x),y(y) {}
};

//ostream 是输出流
ostream& operator << (ostream &out, const Point& p) {
  out << "(" << p.x << "," << p.y << ")";
  return out;
}

//该模板类用来交换两个变量的值
template<typename T>
void swap3(T& a,T& b)
{
	T t = a;
	a = b;
	b = t;
}

int main() {
  Point a(1,2),b(3,4);
  cout<<"a:"<<a<<"  b:"<<b<<endl;
  swap3(a,b);
  cout<<"a:"<<a<<"  b:"<<b<<endl;
  return 0;
}


猜你喜欢

转载自blog.csdn.net/shihunyewu/article/details/52166091