模板类
用模板类定义int string类型的类
用类来实现栈
#include <iostream>
#include <vector>
#include <stdexcept> //throw
//#include <cstdlib> <==> #include <stdlib.h>
using namespace std;
template <class T>
class Stack
{
private:
vector<T> elems; // 元素
public:
void push(T const&); // 入栈
void pop(); // 出栈
T top() const; // 返回栈顶元素
bool empty() const // 如果为空则返回真
{ return elems.empty(); }
};
template <class T>
void Stack<T>::push (T const& elem){
elems.push_back(elem); // 追加传入元素的副本
}
template <class T>
void Stack<T>::pop (){
if (elems.empty())
{ throw out_of_range("Stack<>::pop(): empty stack"); }
elems.pop_back(); // 删除最后一个元素
}
template <class T>
T Stack<T>::top () const
{
if (elems.empty())
{ throw out_of_range("Stack<>::top(): empty stack"); }
return elems.back(); //返回最后一个元素的副本
}
int main()
{
try{
Stack<int> intStack; // int 类型的栈
Stack<string> stringStack; // string 类型的栈
//操作int类型的栈
intStack.push(7);
cout << intStack.top() <<endl;
//操作string类型的栈
stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (exception const& ex){ //catch 异常 of the throw
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
/* result: 7 hello Exception: Stack<>::pop(): empty stack */
模板函数
用来实现不同类型值的比较
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b){
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
模板类的继承
#include <iostream>
#include <string>
using namespace std;
enum eColor { none = 0, red, white};
class Color{
public:
Color(eColor color);
string getStrColor();
protected:
eColor mColor;
};
Color::Color(eColor _color){
mColor = _color;
}
string Color::getStrColor(){
switch (mColor){
case red:return "red";
case white:return "white";
}
}
template <typename T>
class Circle : public Color{
public:
Circle(T radius, eColor color);
T area();
protected:
T radius;//半径r
};
template <typename T>
Circle<T>::Circle(T _radius, eColor _color) : Color(_color){
radius = _radius;
}
template <typename T>
T Circle<T>::area(){
return 3.14 * radius * radius;
}
template <typename T>
class Sphere : public Circle<T>{
public:
Sphere(T radius, eColor color);
T volume();
};
template <typename T>
Sphere<T>::Sphere(T _radius, eColor _color) : Circle<T>::Circle(_radius, _color){}
template <typename T>
T Sphere<T>::volume(){
return 4 * 3.14 * this->radius * this->radius * this->radius / 3;
}
int main(int argc, char* argv[]){
Sphere<double> sphereA(10.0, red);
cout << "Volume: " << sphereA.volume() << endl;
cout << "Area: " << sphereA.area() << endl;
cout << "Color: " << sphereA.getStrColor() << endl;
}