【发布时间】:2014-06-11 22:50:07
【问题描述】:
我创建了一个类模板(称为ThreeVector)并添加了功能以允许不同类型之间的加法操作。这是我的头文件的相关部分:
template <class T>
class ThreeVector {
private:
T mx;
T my;
T mz;
public:
ThreeVector<T>(T, T, T);
template <class X>
ThreeVector<T> operator+(const ThreeVector<X>&);
}
template <class T>
ThreeVector<T>::ThreeVector(T x, T y, T z) { //initialize vector
mx = x;
my = y;
mz = z;
}
template<class T> template<class X>
ThreeVector<T> ThreeVector<T>::operator+(const ThreeVector<X>& a) {
ThreeVector<T> v(mx+a.mx, my+a.my, mz+a.mz);
return v;
}
然后我这样称呼它:
ThreeVector<double> a(1,2,3);
ThreeVector<float> b(4,5,6);
ThreeVector<double> c=a+b;
这给了我错误:
ThreeVector.h: In member function 'ThreeVector<T> ThreeVector<T>::operator+(const ThreeVector<X>&) [with X = float, T = double]':
ThreeVectorTest.cxx:33: instantiated from here
ThreeVector.h:8: error: 'float ThreeVector<float>::mx' is private
ThreeVector.h:122: error: within this context
ThreeVector.h:9: error: 'float ThreeVector<float>::my' is private
ThreeVector.h:123: error: within this context
ThreeVector.h:10: error: 'float ThreeVector<float>::mz' is private
ThreeVector.h:124: error: within this context
make: *** [ThreeVectorTest] Error 1
如果 a 和 b 都是<double>,它就可以正常工作。知道为什么会这样吗?
【问题讨论】:
标签: c++ class templates operator-overloading