类内定义的关键点在于,对应类型要写对,见以下代码例子:
#include<iostream>
using namespace std;
template<class T>
class dyArray {
private:
T *members;
int size1;
public:
dyArray(int a):size1(a) {
members = new T[a];
}
~dyArray() {
delete[] members;
}
T& operator[](int id1) {
return members[id1];
}
void updataID(int idx, T vul) {
members[idx] = vul;
}
};
int main() {
dyArray<double> da1(100);
da1[1] = 1;
da1[2] = 8;
cout << da1[0] << endl;
cout << da1[1] << endl;
dyArray<char> da2(10);
da2[1] = 'a';
da2.updataID(1, 'b');
cout << da2[1] << endl;
return 0;
}
类外实现:保留声明、拷贝声明、加作用域、拷贝实现、模版参数列表声明、指定虚拟类型
以这个为例,来看下这几步(这个是一个构造函数,我们来逐句看下分析内容):
dyArray(int a) :size1(a) {
members = new T[a];
}
以下的代码例子可以在下述例子中找到,这里是为了说明取了部分内容
保留声明(也就是在类中保留类的声明)
template<class T>
class dyArray {
private:
T *members;
int size1;
public:
dyArray(int a);
~dyArray();
T& operator[](int id1);
void updataID(int idx, T vul);
};
拷贝声明(将声明拷贝至类外)
template<class T>
dyArray<T>::dyArray(int a) :size1(a) {
members = new T[a];
}
加作用域(加上类外的作用域)
template<class T>
dyArray<T>::dyArray(int a) :size1(a) {
members = new T[a];
}
拷贝实现(将方法的实现拷贝到类外)
template<class T>
dyArray<T>::dyArray(int a) :size1(a) {
members = new T[a];
}
模版参数列表声明
template<class T>
dyArray<T>::dyArray(int a) :size1(a) {
members = new T[a];
}
指定虚拟类型
template<class T>
dyArray<T>::dyArray(int a) :size1(a) {
members = new T[a];
}
见以下代码示例(均实现了类外实现):
#include<iostream>
using namespace std;
template<class T>
class dyArray {
private:
T *members;
int size1;
public:
dyArray(int a);
~dyArray();
T& operator[](int id1);
void updataID(int idx, T vul);
};
template<class T>
dyArray<T>::dyArray(int a) :size1(a) {
members = new T[a];
}
template<class T>
T& dyArray<T>::operator[](int id1) {
return members[id1];
}
template<class T>
dyArray<T>::~dyArray() {
delete[] members;
}
template<class T>
void dyArray<T>::updataID(int idx, T vul) {
members[idx] = vul;
}
int main() {
dyArray<double> da1(100);
da1[1] = 1;
da1[2] = 8;
cout << da1[0] << endl;
cout << da1[1] << endl;
dyArray<char> da2(10);
da2[1] = 'a';
da2.updataID(1, 'b');
cout << da2[1] << endl;
return 0;
}