14.2.3重学C++之【类模板中成员函数创建时机板】

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;


/*
    1.3.3类模板中成员函数创建时机
        类模板中成员函数和普通类中成员函数创建时机是有区别的:
            普通类中的成员函数一开始就可以创建
            类模板中的成员函数在调用时才创建
*/


class Person1{
public:
    void show_p1(){
        cout << "show_p1" << endl;
    }
};


class Person2{
public:
    void show_p2(){
        cout << "show_p2" << endl;
    }
};


template<class T>
class MyClass{
public:
    T obj;

    void func1(){
        obj.show_p1();
    }

    void func2(){
        obj.show_p2();
    }
};


void test(){
    MyClass <Person1> m;
    m.func1(); // ok
    //m.func2(); // error

    MyClass <Person2> n;
    //n.func1(); // error
    n.func2(); // ok
}


int main(){
    test();

    system("pause");
    return 0;
}

posted @ 2021-04-17 21:19  yub4by  阅读(70)  评论(0)    收藏  举报