函数重载与自动类型转换 Overloading & Auto-Casting
void print(int i);
void print(double i);
print('a'); // 调用 void print(int i),发生自动类型转换
print(3L); // 3L 是 long 型,既可以转换为 int,也可以转换为 double,因此出现冲突,编译报错
函数的默认参数 Default Arguments
int harpo(int n, int m = 4,int j = 5); // 合法
int harpo(int n, int m = 4,int j); // 不合法
beeps = harpo(2); // 等同于 harpo(2, 4, 5)
使用 template
关键字定义模版类
template <class T>
void swap(T& x, T& y)
{
T temp = x;
x = y;
y = temp;
}
template <class T>
void sort(Vector<T>& arr);
class T
指定了一个参数化的类型名,该类型名可在以下场合使用:
模版函数(Template Function) 是函数模版的实例化;编译器会在所需位置根据函数模版与参数类型,生成对应的模版函数
int i = 3, j = 4;
swap(i, j); // 实例化 int 类型的 swap
string s("Hello");
string t("World");
swap(s, t); // 实例化 string 类型的 swap
函数模版的类型推断
void f(float i, float k);
template <class T>
void f(T t, T u);
f(1.0f, 2.0f); // 两个参数都为 float,调用普通函数
f(1.0, 2.0); // 两个参数都为 double,调用函数模版
f(1, 2); // 两个参数都为 int,调用函数模版
f(1, 2.0); // 进行隐式类型转换,将 1、2.0 转换为 1f、2.0f,调用普通函数
<aside> 📌
在 C++ 中:
2.0f
的常量为 float
类型2.0
的常量为 double
类型
</aside>在调用时,可以显式地指明函数模版的类型
template <class T>
void foo(){...}
foo<int>();
foo<float>();
类模版的声明和实现都应放在头文件中
模版可以接收一或多个类型参数
template <class T>
class Vector{
public:
Vector(int);
~Vector();
Vector(const Vector&);
Vector& operator=(const Vector&);
T& operator[](int);
private:
T* m_elements;
int m_size;
}
Vector<int> v1(100);
v1[20] = 10;
template <class Key, class Value>
class HashTable{
const Value& lookup(const Key&) const;
void insert(const Key&, const Value&);
};
模版可以嵌套,即模版实例可以作为外层模版的类型参数
Vector < Vector <double> >
// 一个存储 double 类型的 Vector 的 Vector