C++类模板的问题

Issues with C++ Class templates

本文关键字:问题 C++      更新时间:2023-10-16

我在Student.h 中有以下代码

#ifndef _student_h_
#define _student_h_
template  <class T>
class Student
{
public:
    Student();
    ~Student();
    void setWage(float hourlyWage);
    void addHours(float hoursWorked);
    bool pay();
    bool writeCheck(float value);
    float getTotalEarnings();
    float getStudentCut();
    float getSwauCut();
    float getWage();
private:
    float wage;
    float hours;
    float swauCut;
    float studentCut;
    float totalEarnings;
};
#include "student.tpp" //Works with .tpp, errors with .cpp
#endif

当我试图分离我的代码时,我试图将以下代码放入.cpp和.tpp中进行测试。

#pragma once
#include "stdafx.h"
#include "Student.h"
template <class T>
Student<T>::Student()
{
    wage = 0.0f;
    hours = 0.0f;
    swauCut = 0.0f;
    studentCut = 0.0f;
    totalEarnings = 0.0f;
}
template <class T>
Student<T>::~Student()
{
}
template <class T>
void Student<T>::setWage(float hourlyWage)
{
    wage = hourlyWage;
}
template <class T>
void Student<T>::addHours(float hoursWorked)
{
    hours += hoursWorked;
}
template <class T>
bool Student<T>::pay()
{
    if (hours == 0 || wage == 0)
        return false;
    studentCut += .25*(hours * wage);
    swauCut += .75*(hours * wage);
    totalEarnings += hours * wage;
    hours = 0.0f;
    return true;
}
template <class T>
bool Student<T>::writeCheck(float value)
{
    if (value < studentCut){
        studentCut -= value;
        return true;
    }
    return false;
}
template <class T>
float Student<T>::getTotalEarnings()
{
    return totalEarnings;
}
template <class T>
float Student<T>::getStudentCut()
{
    return studentCut;
}
template <class T>
float Student<T>::getSwauCut()
{
    return swauCut;
}
template <class T>
float Student<T>::getWage()
{
    return wage;
}

我的问题是,如果我使用.cpp文件并注释掉tpp文件,我会得到各种各样的错误。然而,如果我只是#include Student.tpp,文件编译得很好,可以工作。我的印象是cpp和tpp是相对相同的吗?

我得到的错误是:

Error1  error C2995: 'Student<T>::Student(void)' : function template has already been defined   c:usersaurelib.csdesktopstudentprojectstudentprojectstudent.cpp   13  1   StudentProject
Error2  error C2995: 'Student<T>::~Student(void)' : function template has already been defined  c:usersaurelib.csdesktopstudentprojectstudentprojectstudent.cpp   18  1   StudentProject

用于所有功能。

如果我从.cpp文件中删除#include "Student.h",我会得到语法错误。

我正在使用Visual Studio。正如我所说,当我在模板底部#include "Student.tpp"时,我没有问题。但当我使用相同的代码和#include "Student.cpp"时。

提前感谢!

我的猜测是:

当您将包含类成员函数实现的文件命名为Student.cpp时,编译器会尝试对其进行编译。当您将其命名为Student.tpp时,编译器不会尝试编译它。

在您的文件中,Student.h#include是Student.cppStudent.cpp#include则是Student.h。当预处理器充实Student.cpp的内容时,它最终会包含两次文件的内容。这就是为什么会出现function template has already been defined错误。

预防方法:

  1. 不要将文件命名为Student.cpp。您可以使用Student.tpp,也可以使用更具描述性的名称Student_Impl.h

  2. 除了使用#pragma once之外,还在文件中添加#include防护。

    #pragma once
    #ifndef _student_impl_h_
    #define _student_impl_h_