1.3.3 类模板中成员函数的创建时机

94 阅读1分钟

类模板中成员函数在调用时才去创建。

#include <iostream>

using namespace std;

class Person1
{
public:
	void show_person1()
	{
		cout << "person1 show" << endl;
	}
};

class Person2
{
public:
	void show_person2()
	{
		cout << "person2 show" << endl;
	}
};

template<class T>
class MyClass
{
public:
	T obj;
	void func1()
	{
		obj.show_person1();
	}
	void func2()
	{
		obj.show_person2();
	}
};

void test()
{
	MyClass<Person1> m;
	m.func1();
	MyClass<Person2> m;
	m.func2();
}

int main()
{
	test();

	system("pause");
	return 0;
}