我在Student.h问题与C++类模板
#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
....所有的功能。
如果我从.cpp
文件中删除#include "Student.h"
,我得到语法错误。
我正在使用Visual Studios。而且就像我说的,当我在模板的底部输入#include "Student.tpp"
时,我没有问题。但是当我使用相同的代码和#include "Student.cpp"
。
非常感谢!
删除所有''秒。但是请注意,模板代码不应该放在'.cpp'文件中,除非它包含在标题中,否则可能会导致更多混淆而不是欢乐。但是,为什么您首先将该课程作为模板?我看不到任何地方使用的模板参数。 –
Biffen
2014-09-25 16:59:15
为什么'学生'是第一名的模板课?我无法在任何地方找到使用'typename T'的任何声明。看你在这里有一个XY问题。 – 2014-09-25 17:02:17
它实际上并不需要。它只是一个概念。该计划将接受WriteCheck函数中的T对象而不是float。一切正常,我只是想知道为什么我不能使用CPP,并被迫进入.tpp。而托马斯,我通过阅读这个问题开始了程序的运行。但我不认为这是解释为什么tpp选择cpp。以及为什么cpp根本不起作用 – 2014-09-25 17:06:09