【问题标题】:what means “error: overloaded 'operator*' must have at least one parameter of class or enumeration type”什么意思“错误:重载的'operator *'必须至少有一个类或枚举类型的参数”
【发布时间】:2015-07-27 17:46:43
【问题描述】:

我正在编写一个数学库。我使用 C++ 的模板来完成它。

有两种代码。一个好吗?但是另一个不好?为什么?

错误日志:

../test_vector/main.cpp:98:10: 错误:重载 'operator*' 必须至少有一个类或枚举类型的参数 内联 T 运算符*(float s,const T &t)

#include <cmath>

namespace gqm
{

template <typename T>
struct vector2 {
    vector2() {}
    vector2(T x, T y) : x(x), y(y) {}
    vector2 operator*(float s) const
    {
        return vector2(x * s, y * s);
    }
    T x;
    T y;
};


//it works good!
template <typename T>
inline T operator*(float s,const T &t)
{
    return t.operator*(s);
}

//it do not works!Why?
//template <typename T>
//inline T operator*(float s,const T &t)
//{
//    return t*s;
//}

typedef vector2<float> vec2;

}//namespace gqm

int main()
{
    gqm::vec2 v2 = 0.5 * gqm::vec2(1.0,1.0);

    return 0;
}

【问题讨论】:

  • 你用的是什么编译器? GCC 4.8.4 没问题
  • 尝试编译您实际发布的内容......可能在“真实代码”中您输入了“不工作!”部分位于vector2 的类定义中
  • 或者你用内置类型实例化了模板

标签: c++ templates


【解决方案1】:

你不能重载这个操作符,因为你有相同的参数并且返回相同的类型。 如果您评论第一个,第二个也可以。

【讨论】:

  • 取消注释它们都会导致重新定义错误(先前声明...),这与操作的错误不匹配。我不认为他取消了这两个功能的注释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多