1.模板的定义
在重载中,我们可以根据参数的不同来调用不同的函数,以达到重载,但是如果想实现代码的重用 C++模板再好不过了。模板能实现数据类型的参数化。即把类型当成参数
#include<stdio.h>
template <typename T>
T max(T x,T y)
{
return (x>y)? x:y;
}
int main()
{
printf("%d", max<int>(3,8));
return 0;
}
第一次写直接输出的时候格式不太正确。
2 模板分为函数模板和类模板
class CTest {
public:
CTest(int i);
CTest(const CTest& rhs);
CTest& operator=(const CTest& rhs);//operator用于(赋值号)重载,返回类的对象的指针
void printCTest(const CTest& rhs);
private:
int value;
};
CTest::CTest(int i):value(i)
{
cout<<"Contructor of CTest"<<endl;
}
CTest::CTest(const CTest& rhs):value(rhs.value)
{
cout<<"Copy contructor of CTest"<<endl;
}
CTest& CTest::operator=(const CTest& rhs)
{
cout<<"Assign function of CTest"<<endl;
if(this == &rhs)
return *this;
value = rhs.value; //通过对象访问私有成员变量
return *this;
}
void CTest::printCTest(const CTest& rhs)
{
cout<<rhs.value<<endl; //通过对象访问私有成员变量
}
int main()
{
CTest t = 1;
CTest tt = 2;
// cout<<t.value<<endl; //通过对象访问私有成员变量,编译错误
// cout<<tt.value<<endl; //通过对象访问私有成员变量,编译错误
t.printCTest(tt);
}
这个例子中主要先讲了operator作为重载操作符的典型例子,
下一篇再讨论模板的两种具体情况