【发布时间】:2014-11-17 11:22:09
【问题描述】:
下面的代码不起作用,我找不到原因,非常感谢任何帮助。
//In Maths.h file
template <class T> class Maths{
public:
Maths<T>(T lhs);
template<typename U>
Maths<T>(const Maths<U>& otherMaths);
~Maths();
template <typename U>
Maths<T>& operator+(const Maths<U>& rhs);
template <typename U>
Maths<T>& operator*(const Maths<U>& rhs);
template <typename U>
Maths<T>& operator-(const Maths<U>& rhs);
private:
T _lhs;
};
//In Maths.cpp file
#include "Maths.h"
template <class T>
Maths<T>::Maths(T lhs){
_lhs = lhs;
return _lhs;
}
template <class T> template <typename U>
Maths<T>::Maths(const Maths<U>& otherMaths){
_lhs = otherMaths._lhs;
}
template <class T>
Maths<T>::~Maths(){}
template <class T> template <typename U>
Maths<T> Maths<T>::operator+(const Maths<T>& rhs){ return Maths._lhs + rhs; }
template <class T> template <typename U>
Maths<T> Maths<T>::operator-(const Maths<T>& rhs){ return Maths._lhs - rhs; }
template <class T> template <typename U>
Maths<T> Maths<T>::operator*(const Maths<T>& rhs){ return Maths._lhs * rhs; }
问题在于 VS 无法识别关键字运算符(即不显示为蓝色),这是为什么呢?
编辑:
我已经删除了下面指出的错误。将所有定义移到 .h 文件中,代码仍然无法编译,此处发现错误:http://i.imgur.com/Z9rWOFh.png
新代码(如果有兴趣):
//in Maths.h file
template <class T> class Maths{
public:
Maths<T>(T lhs);
template<typename U>
Maths<T>(const Maths<U>& otherMaths);
~Maths();
T& getValue(){ return _lhs; };
template <typename U>
Maths<T>& operator+(const Maths<U>& rhs);
template <typename U>
Maths<T>& operator*(const Maths<U>& rhs);
template <typename U>
Maths<T>& operator-(const Maths<U>& rhs);
private:
T _lhs;
};
template <class T>
Maths<T>::Maths(T lhs){
_lhs = lhs;
}
template <class T> template <typename U>
Maths<T>::Maths(const Maths<U>& otherMaths){
_lhs = otherMaths.getValue();
}
template <class T>
Maths<T>::~Maths(){}
template <class T>
Maths<T> Maths<T>::operator+(const Maths<T>& rhs){ return _lhs + rhs.getValue(); }
template <class T> template <typename U>
Maths<T> Maths<T>::operator-(const Maths<U>& rhs){ return _lhs - rhs.getValue(); }
template <class T> template <typename U>
Maths<T> Maths<T>::operator*(const Maths<U>& rhs){ return _lhs * rhs.getValue(); }
//in main.cpp
#include "Maths.h"
int main(){
Maths<int> x = 1;
Maths<int> y = 5;
x + y;
return 0;
}
【问题讨论】:
-
您不需要在
Maths之后为您的内联成员函数返回类型指定<T>,也不需要为构造函数名称指定。 -
请阅读Why can templates only be implemented in the header file? 然后,我建议使用 g++ 或 clang++ 以获得可以理解的错误消息:coliru.stacked-crooked.com/a/9aaa7134ef8a6c28
-
我建议你阅读this - 你有很多基本错误。
-
@TonyD 我更担心 VS 不将运算符识别为关键字的原因。这段代码(连同我拥有的 main.cpp)在 g++ 中运行良好,但我在大学课程的要求是代码要在 VS 上运行。您能看到我的代码无法将运算符识别为关键字的任何原因吗? (例如:在上面的代码 sn-p 上它读起来很好,而在 VS 上它看起来像这样i.imgur.com/upahPNx.png)
-
如果某些东西适用于 g++ 并不意味着它应该适用于另一个编译器。有些行为在标准上是未定义的,有些编译器实现了“预期的”行为,而另一些则没有。我强烈建议您修复 cmets 和 answers 指出的错误,然后看看它是否仍然不起作用。
标签: c++ class templates syntax overloading