马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
第四十三课到四十六课(函数模板)
template<class T>
void swap(T &a, T &b)
{
T tem = a;
a = b;
b = tem;
}
注:
1.函数模板的原型和实现要在一起,不然会出错
2.template<class T>class不代表一个类,而是一个类型,一可以换位typename
3.swap<int>(i1,i2)可以明确告诉编译器使用什么类型
类模板:
template<class T>
class Stack
{
public:
Stack(xxx);
push(T value);
T pop();
~Stack();
protected:
T *data;
unsigned int size;
unsigned int sp;
};
写类模板内的函数时候要Stack<T>::Stack(xxx)加上<type>
调用时候也要加上Stack<T> xxx;
函数模板:
#include<iostream>
#include<string>
template<typename T>
void swap(T &a,T &b)
{
T temp = a;
a = b;
b = temp;
}
void main()
{
int a = 1;
int b = 2;
std::cout << "a = " << a << ",b = " << b << "\n\n";
swap<int>(a,b);
std::cout << "a = " << a << ",b = " << b << "\n\n";
std::string s1 = "小乌龟";
std::string s2 = "鸹貔乌龟";
std::cout << "s1 = " << s1 << ",s2 = " << s2 << "\n\n";
swap<std::string>(s1,s2);
std::cout << "s1 = " << s1 << ",s2 = " << s2 << "\n\n";
}
类模板:
#include<iostream>
#include<string>
template<class T>
class Stack
{
public:
Stack(unsigned int size = 100)
{
this->size = size;
data = new T[size];
sp = 0;
}
Stack(Stack &rhs)
{
*this = rhs;
}
Stack &operator= (Stack &rhs)
{
if(this != &rhs)
{
this->data = new T[size];
unsigned temsp = rhs.sp; //保存rhs的栈指针sp
while(rhs.sp > 0)
{
//temsp--;
data[rhs.sp] = rhs.pop();
}
this->sp = temsp;
this->size = rhs.size;
rhs.sp = temsp;
}
else
{
std::cout << "相同的两个类\n";
}
return *this;
}
~Stack()
{
delete []data;
}
void push(T value) throw(const char *)
{
if(sp == size)
throw "栈满!";
data[sp++] = value;
}
T pop() throw (const char *)
{
if(sp == 0)
throw "栈空!";
return data[--sp];
}
protected:
unsigned int size;
unsigned int sp;
T *data;
};
void main()
{
Stack<int> stack;
try
{
stack.push(1);
stack.push(2);
stack.push(3);
// std::cout << stack.pop() << "\n";
// std::cout << stack.pop() << "\n";
// std::cout << stack.pop() << "\n";
// std::cout << stack.pop() << "\n";
}
catch(char *a)
{
std::cout << a << "\n";
}
Stack<int> stack2 = stack;
std::cout << stack2.pop() << "\n";
}
|