模板的概念:
class或typename表示的是任何类型的意思。
#include<iostream> using namespace std; template<typename T> T getmax(T a, T b)//类型进行参数化,返回值也是T类型的 { if (a > b) return a; else return b; }; int main() { cout << getmax(1, 7) << endl;//实例化getmax(int,int) cout << getmax('h', 'v') << endl;//实例化getmax(char,char) cout << getmax(1.213213,3.4324234) << endl; return 0; }
类模板 :
类模板的成员函数其实都是函数模板:
类模板的成员函数可以放在类模板的定义体中,与普通成员函数定义方法一样,如show()
也可以放在类模板的外部定义,如getmax(),当做形参
//类模板
#include<iostream>
using namespace std;
template<typename T,int size>//类模板
class Data
{
T data[size];//注意这是在模板中,在main中size必须要被初始化
public:
Data()//构造函数
{
cout << "input " << size << "datas:" << endl;
for (int i = 0; i < size; i++)
cin >> data[i];
}
void show()
{
cout << size << " datas:" << endl;
for (int i = 0; i < size; i++)
cout << data[i]<<endl;
}
T getmax();
};
template<typename T,int size>
T Data<T, size>::getmax()//
{
T max = data[0];
for (int i = 0; i < size; i++)
{
if (data[i] > max)
{
max = data[i];
}
}
return max;
};
int main()
{
Data<int,5> d;//模班类
d.show();
cout << d.getmax() << endl;
return 0;
}
函数模板:
template<typename T>
void MySwap(T& a,T& b)
{
T temp = a;
a = b;
b = temp;
}
函数模板实例化成模板函数:
#include<iostream>
using namespace std;
//交换两个变量
template<typename T>//typename,class
void MySwap(T& a,T& b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10, b = 20;
MySwap(a, b);//模板函数
printf("%d\n", a);
printf("%d", b);
return 0;
}
- 当函数重载与模板函数冲突时,优先调用普通函数
特化
操作符重载:
重载进行复数的加法和乘法:
加法
Complex Add(Complex& other)
{
//this指针是一个局部变量,局部于某个对象,对象指针访问成员用->
return Complex(this->real + other.real, this->image + other.image);
}
Complex operator+(Complex& other)
{
//this指针是一个局部变量,局部于某个对象,对象指针访问成员用->
return Complex(this->real + other.real, this->image + other.image);
}
cout输出进行重载:
#include<iostream>
using namespace std;
class Complex
{
public:
double real;
double image;
Complex(double real,double image):real(real),image(image){}
Complex operator*(Complex& other)
{
double a = this->real;
double b = this->image;
double c = other.real;
double d = other.image;
return Complex(a * c - b * d, b * c + a * d);
}
Complex Add(Complex& other)
{
//this指针是一个局部变量,局部于某个对象,对象指针访问成员用->
return Complex(this->real + other.real, this->image + other.image);
}
Complex operator+(Complex& other)
{
//this指针是一个局部变量,局部于某个对象,对象指针访问成员用->
return Complex(this->real + other.real, this->image + other.image);
}
};
//输出重载
ostream& operator << (ostream &cout, const Complex & other)
{
cout << other.real << "," << other.image << "i";
return cout;
}
int main()
{
Complex c1(1.0f, 2.0f);
Complex c2(2.0f, 2.0f);
Complex c3 = c1 + c2;
Complex c4 = c1 * c2;
cout << c4 << endl;
cout << c3<<endl;
}
版权声明:本文为Neo_21原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。