雪傲天1 2023-01-08 18:27 采纳率: 96.2%
浏览 31
已结题

类模板成员函数类外实现的编译错误,不知道哪里错了

在学习类模板成员函数类外实现遇到了三个错误,水平有限,请大家帮我解决一下


#include<iostream>
using namespace std;
#include<string>
template<class T1,class T2>
class Person
{
public:
    Person(T1 name,T2 age);
    T1 m_Name;
    T2 m_Age;
};
//构造函数类外实现
template<class T1,class T2>
Person<T1.T2>::Person(T1 name,T2 age)
{
    this->m_Name=name;
    this->m_Age=age;
}
template<class T1,class T2>
void Person<T1,T2>::showPerson()
{
    cout<<"name:"<<this->m_Name<<"age:"<<this->m_Age<<endl;
}
void test01()
{
    Person<string,int> P("Tom",20);
    P.showPerson();
}
int main()
{
    test01();
    system("pause");
    return 0;
}

三个错误原因是
错误 1 error C2143: 语法错误 : 缺少“,”(在“.”的前面)
错误 2 error C2649: “typename”: 不是“class”
错误 3 fatal error C1004: 发现意外的文件尾

  • 写回答

1条回答 默认 最新

  • cjh4312 2023-01-08 19:11
    关注
    
    #include <iostream>
    using namespace std;
    #include <string>
    template <class T1, class T2>
    class Person
    {
    public:
        Person(T1 name, T2 age);
        T1 m_Name;
        T2 m_Age;
        void showPerson();
    };
    // 构造函数类外实现
    template <class T1, class T2>
    Person<T1, T2>::Person(T1 name, T2 age) 
    {
        this->m_Name = name;
        this->m_Age = age;
    }
    template <class T1, class T2>
    void Person<T1, T2>::showPerson()
    {
        cout << "name:" << this->m_Name << "age:" << this->m_Age << endl;
    }
    void test01()
    {
        Person<string, int> P("Tom", 20);
        P.showPerson();
    }
    int main()
    {
        test01();
        system("pause");
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 2月5日
  • 已采纳回答 1月28日
  • 创建了问题 1月8日