【问题标题】:Defining operation between different types with templates使用模板定义不同类型之间的操作
【发布时间】: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 都是&lt;double&gt;,它就可以正常工作。知道为什么会这样吗?

【问题讨论】:

标签: c++ class templates operator-overloading


【解决方案1】:

类模板的访问权限可能有点混乱。

假设你有一个简单的类模板。

template <typename T>
class A
{
   public:
      A() {}

   private:
      T data;
};

当您使用 A 创建实例时,

A<int> a1;
A<float> a2;

您正在使用模板定义两个类。就好像你有两个班级:

class AInt
{
   public:
     AInt() {}
   private:
     int data;
};

class AFloat
{
   public:
     AFloat() {}
   private:
     float data;
};

很容易看出AInt 无权访问AFloat 的私有部分,反之亦然。

A&lt;int&gt;A&lt;float&gt; 也是如此。

为了使您的operator+ 功能正常工作,您有两个选择:

  1. 公开类模板的成员。
  2. 有这样的朋友声明:

    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 X> friend class ThreeVector;
    };
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多