普通类的成员函数的话,在刚开始就创建出来了,但是类模版中的成员函数的话,只有在具体调用运行的时候才会被创建,可见以下代码例子:
#include<iostream>
using namespace std;
class people1 {
public:
void run() {
cout << "跑" << endl;
}
};
class circle1 {
public:
void hua() {
cout << "画" << endl;
}
};
template<class T>
class tst {
T sq;
public:
void msg1() {
sq.run();
}
void msg2() {
sq.hua();
}
};
int main() {
tst<people1> sq1;
sq1.msg1(); // 这会才创建
tst<circle1> sq2;
sq2.msg2();
return 0;
}
类模版函数传参有三种,可见以下代码示例:
#include<iostream>
using namespace std;
template<class Msg1, class Msg2>
class people {
public:
people(Msg1 msg_1, Msg2 msg_2) {
this->msg1 = msg_1;
this->msg2 = msg_2;
}
private:
Msg1 msg1;
Msg2 msg2;
};
// 1,直接指定类型
void tst1(people<string, int>& p1) {
}
// 2,参数模版化
template<class T1, class T2>
void tst2(people<T1, T2> &p1) {
}
// 3,类模版化
template<class T>
void tst3(T &p1) {
}
int main() {
people<string, int> p1("王五", 180);
tst1(p1);
tst2(p1);
tst3(p1);
return 0;
}
类模版继承可见下,也是非常直观的,看代码理解即可:
#include<iostream>
using namespace std;
template<class Msg1, class Msg2>
class people {
public:
people(Msg1 msg_1, Msg2 msg_2) {
this->msg1 = msg_1;
this->msg2 = msg_2;
}
private:
Msg1 msg1;
Msg2 msg2;
};
template<class T1, class T2, class T3>
class people2 : public people<T1, T2> {
T3 t3;
};
int main() {
people<string, int> p1("王五", 180);
return 0;
}
标签:传参,p1,msg1,函数,people,模版,msg2,msg
From: https://blog.csdn.net/qq_43355454/article/details/145044001