要点
- 模板函数在类的外部定义
- 友元函数在类的外部定义(<<的重载)
- 模板类中静态变量的使用规则
示例
Array.h
#pragma once
#include<iostream>
using namespace std;
template<typename T>
class Array
{
private:
int len;
T *data;
friend ostream& operator<<<T>(ostream &out, Array<T>& array);
public:
static int x;
static T y;
Array(int len);
~Array();
int getLen();
T* getData();
T& operator[] (int index);
Array<T>& operator=(Array<T>& array);
Array(Array<T>& array);
};
Array.cpp
#include "stdafx.h"
#include "Array.h"
#include<iostream>
using namespace std;
template<typename T>
Array<T>::Array(int len)
{
this->len = len;
if(len>0)
this->data = new T[len];
else{
this->data = NULL;
}
}
template<typename T>
Array<T>::~Array()
{
if (this->data != NULL) {
delete []this->data;
}
}
template<typename T>
int Array<T>::getLen()
{
return this->len;
}
template<typename T>
T * Array<T>::getData()
{
return this->data;
}
template<typename T>
T& Array<T>::operator[](int index)
{
return this->data[index];
}
template<typename T>
Array<T> & Array<T>::operator=(Array<T>& array)
{
cout << "执行=运算" << endl;
if (this->data != NULL) {
delete[]this->data;
}
this->len = array.getLen();
this->data = new T[len];
for (int i = 0; i < len; i++) {
this->data[i] = array[i];
}
return *this;
}
template<typename T>
Array<T>::Array(Array<T>& array)
{
cout << "执行copy构造函数" << endl;
this->len = array.getLen();
this->data = new T[this->len];
for (int i = 0; i < this->len; i++) {
this->data[i] = array[i];
}
}
template<typename T>
ostream& operator<<(ostream &out, Array<T>& array) {
for (int i = 0; i < array.len; i++) {
out << array[i]<<" ";
}
out << endl;
return out;
}
template<typename T>
int Array<T>::x = 10;
template<typename T>
T Array<T>::y;
test.cpp
// ArrayDemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Array.cpp"
#include "iostream"
using namespace std;
int main()
{
Array<int> array(2);
array[0] = 1;
array[1] = 2;
cout <<"array =>"<< array;
Array<int> array1 = array;
cout << "array1=>" << array1;
Array<int> array2(3);
array2[0] = 10;
array2[1] = 20;
array2[2] = 30;
cout << "array2=>" << array2 ;
array2 = array;
cout << "array2=>" << array2;
cout << "Array<int>::x =>" << Array<int>::x << endl;
Array<int>::x = 100;
Array<char>::x = 1;
cout << "Array<int>::x =>"<<Array<int>::x << endl;
cout <<"Array<char>::x =>"<< Array<char>::x << endl;
Array<float>::y = 1000;
cout << Array<float>::y << endl;
return 0;
}
运行结果: