类模板中成员函数和普通类中成员函数创建时机是有区别的:

    • 普通类中的成员函数一开始就可以创建
    • 类模板中的成员函数在调用时才创建
    1. #include<iostream>
    2. #include<string>
    3. using namespace std;
    4. //类模板中成员函数创建时机
    5. //类模板中成员函数在调用时才去创建
    6. class Person1
    7. {
    8. public:
    9. void showPerson1()
    10. {
    11. cout << "Person1 show" << endl;
    12. }
    13. };
    14. class Person2
    15. {
    16. public:
    17. void showPerson2()
    18. {
    19. cout << "Person2 show" << endl;
    20. }
    21. };
    22. template<class T>
    23. class MyClass
    24. {
    25. public:
    26. T obj;
    27. //类模板中的成员函数
    28. void func1()
    29. {
    30. obj.showPerson1();
    31. }
    32. void func2()
    33. {
    34. obj.showPerson2();
    35. }
    36. };
    37. void test01()
    38. {
    39. MyClass<Person1> m;
    40. m.func1();
    41. //m.func2(); //编译会出错,说明函数调用才会去创建成员函数
    42. }
    43. int main(void)
    44. {
    45. test01();
    46. system("pause");
    47. return 0;
    48. }