C ++类模板的问题

时间:2014-09-25 16:54:00

标签: c++ visual-studio-2012

我在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:\users\aurelib.cs\desktop\studentproject\studentproject\student.cpp   13  1   StudentProject
Error2  error C2995: 'Student<T>::~Student(void)' : function template has already been defined  c:\users\aurelib.cs\desktop\studentproject\studentproject\student.cpp   18  1   StudentProject

....用于所有功能。

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

我正在使用Visual Studios。就像我说的那样,当我在模板底部#include "Student.tpp"时,我没有问题。但是当我使用相同的代码和#include "Student.cpp"代替时。

提前非常感谢!

1 个答案:

答案 0 :(得分:0)

我的猜测是:

当您命名包含类成员函数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 guards。

    #pragma once
    #ifndef _student_impl_h_
    #define _student_impl_h_