c++ - “error: overloaded ' 运算符 *' must have at least one parameter of class or enumeration type” 是什么意思

标签 c++ templates

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

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

错误日志:

../test_vector/main.cpp:98:10: error: overloaded 'operator*' must have at least one parameter of class or enumeration type inline T operator*(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;
}

最佳答案

你不能重载这个运算符,因为你在两者中有相同的参数并返回相同的类型。 如果您评论第一个,第二个也可以。

关于c++ - “error: overloaded ' 运算符 *' must have at least one parameter of class or enumeration type” 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31649388/

相关文章:

c++ - 将零分配给指针会破坏分配的内存吗?

xml - 如何在odoo的电子邮件模板中添加来自其他模型的字段?

wpf - 我如何从代码中的模板对象获取实际的 XAML(或者我可以)?

c++ - std::function:参数的严格编译时验证

c++ - 是否可以在模板特化中匹配模板化基础?

c++ - 将指针数组初始化为空指针

c++ - 如何使类在 vector 内可排序?

c++ - 微型 C++ 结构的行为

c++ - `*this` 外部成员函数体?

C++ - 获取模板的类型名称,其中该类用作另一个模板