template或template
class 类名{private: T a;};
注意事项:
模板类是一个抽象类,定义对象时需要参数类型的传入
具体实现如下:
#include
using namespace std;
template
class A {
public:
void seta(T &a) {
this->a = a;
}
void printA() {
cout << this->a << endl;
}
protected:
T a;
};
int main() {
int x = 888;
A a1;
a1.seta(x);
a1.printA();
char xx = ‘x’;
A a2;
a2.seta(xx);
a2.printA();
return 0;
}
② 模板类被具体类继承:
基本语法:
定义: class 具体类名 :public 模板类名<参数类型>{};
继承后的操作与普通类之间继承一样;
实现方法如下:
#include
using namespace std;
template
class A {
public:
void seta(T &a) {
this->a = a;
}
void printA() {
cout << this->a << endl;
}
protected:
T a;
};
class B :public A {
private:
int b;
public:
void setb(int b) {
this->b = b;
}
void printB() {
cout << this->b << endl;
}
};
int main() {
int x = 888;
B b1;
b1.setb(999);
b1.printB();
b1.seta(x);
b1.printA();
return 0;
}
③ 模板类被模板类继承
类继承:
基本语法:
template
class 模板类名 :public 基类模板类名{ };
具体实现方法:
#include
using namespace std;
template
class A {
public:
void seta(T &a) {
this->a = a;
}
void printA() {
cout << this->a << endl;
}
protected:
T a;
};
template
class C :public A {//----------语法所在地
private:
T c;
public:
void setC(T &c) {
this->c = c;
}
void printC() {
cout << this->c << endl;
}
};
class B :public A