【问题标题】:C++ Using the operator keyword with a template?C++ 在模板中使用运算符关键字?
【发布时间】:2012-07-04 13:10:17
【问题描述】:

我正在努力定义友元运算符函数。我的代码如下:

    template <typename typ>
    class VecClass 
    {
     public:
        VecClass();
        /* other class definitions */
        friend void operator+(VecClass op1,VecClass op2);
    }

    template <typename typ>
    void VecClass<typ>::operator+(VecClass<typ> &op1,VecClass<typ> &op2)
    {
        /* do some stuff on op1 and op2 in here */
    }

其中 VecClass 是一个用于创建向量并在这些向量上执行各种功能的类(注意,我已经简化了代码以尝试尽可能清晰)。编译时,使用

    int main()
    {
        VecClass=a,b;
        a+b;
        return 0;
    }

我得到以下编译错误

     error C2039: '+' : is not a member of 'VecClass<typ>'

我显然遗漏了一些东西,如果有任何建议,我将不胜感激。谢谢。

【问题讨论】:

  • friend 函数不是成员函数。

标签: c++ templates operator-overloading friend


【解决方案1】:

你声明了一个友元操作符,而不是类成员,所以删除VecClass&lt;typ&gt;::

template <typename typ>
void operator+(VecClass<typ> &op1,VecClass<typ> &op2)
{
        /* do some stuff on op1 and op2 in here */
}

【讨论】:

  • 或者你也可以删除friend关键字。
  • 在任何一种情况下,请注意签名不匹配:朋友声明接受对象,模板定义接受引用。
  • @ChristianStieber:确实。最好的选择都不是;这是一个常量引用。
  • @SingerOfTheFall:没用。运算符 + 是二元函数,而不是三元函数。如果去掉friend关键字,该运算符的签名必须是VecClass operator +(const VecClass&);
  • 感谢所有答案和 cmets,它们帮助我找到了解决方案。当我真的应该在朋友定义中指定类型名时,我在实现一个包含模板类型名的朋友运算符时陷入困境 - 否则我可能会尝试将运算符应用于不同类型的对象。例如,对于一个特定的重载运算符,我现在有:friend VecClass&lt;double&gt; operator+(const double a,VecClass&lt;double&gt; &amp;rhs); 和定义 VecClass&lt;double&gt; operator+(const double a,const VecClass&lt;double&gt; &amp;rhs{...}
猜你喜欢
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多