马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Luck is what you have left over after you give 100 percent.
类模板成员函数类外实现#include<iostream>
#include<string>
using namespace std;
template<class T1,class T2>
class Student
{
public:
T1 m_name;
T2 m_num;
//成员函数类内声明
Student(T1 name,T2 num);
void showstudent();
};
//构造函数 内外实现
template<class T1,class T2>
Student<T1,T2>::Student(T1 name,T2 num)
{
this->m_name = name;
this->m_num = num;
}
//成员函数 类外实现
template<class T1,class T2>
void Student<T1,T2>::showstudent()
{
cout << "name : " << this->m_name << " num : " << this->m_num << endl;
}
void test1()
{
Student<string,int>p("回锅肉",50);
p.showstudent();
}
int main()
{
test1();
return 0;
}
类模板分文件编写
1、直接包含.cpp源文件
2、将声明和实现写到同一个文件中,并更改后缀名为.hpp(hpp是约定的名称不是强制)
类模板和友元
全局函数类内实现——直接在类内声明友元
全局函数类外实现——需提前让编译器知道全局函数的存在#include<iostream>
#include<string>
using namespace std;
//全局函数配合友元类外实现
//函数声明模板->函数模板定义->友元
//增加类模板声明
template<class T1,class T2>
class Student;
//需要将实现体写在前面让编译器看到 也可以将实现体写到后面
//实现体写在后面,先声明
template<class T1,class T2>
void showstudent3(Student<T1,T2>&p);
//实现体写在前面
template<class T1,class T2>
void showstudent2(Student<T1,T2>&p)
{
cout << "showstudent2!!!!!!!!!!!!!!!!!" << endl;
cout << " name : " << p.m_name << " num : " << p.m_num << endl;
}
template<class T1,class T2>
class Student
{
//全局函数类内实现
friend void showstudent1(Student<T1,T2>&p)
{
cout << "showstudent1!!!!!!!!!!!!" << endl;
cout << "name : " << p.m_name << " num : " << p.m_num << endl;
}
//全局函数类外实现 类内声明
//加空模板参数列表
friend void showstudent2<>(Student<T1,T2>&p);
friend void showstudent3<>(Student<T1,T2>&p);
public:
T1 m_name;
T2 m_num;
Student(T1 name,T2 num)
{
this->m_name = name;
this->m_num = num;
}
};
//实现体实现
template<class T1,class T2>
void showstudent3(Student<T1,T2>&p)
{
cout << "showstudent3!!!!!!!!!!!!!!!!!" << endl;
cout << " name : " << p.m_name << " num : " << p.m_num << endl;
}
void test1()
{
Student<string,int>a("上上谦",99999);
showstudent1(a);
showstudent2(a);
showstudent3(a);
}
int main()
{
test1();
return 0;
}
我又来喽
|