【问题标题】:simple c++: How to overload the multiplication operator so that float*myClass and myClass*float works简单的 C++:如何重载乘法运算符,以便 float*myClass 和 myClass*float 工作
【发布时间】:2012-05-08 10:52:06
【问题描述】:
class MyClass;

int main()
{
  float a = 5;
  MyClass c1;
  MyClass c2 = a*c1;
  MyClass c3 = c1*a;
}

如何重载乘法运算符以使 a*c1 和 c1*a 都能工作?

【问题讨论】:

  • MyClass 有哪些构造函数?是否可以从float 隐式转换?

标签: c++ operator-overloading


【解决方案1】:

像这样:

MyClass operator* (float x, const MyClass& y)
{
    //...
}

MyClass operator* (const MyClass& y, float x)
{
    //...
}

第二个也可以是成员函数:

class MyClass
{
    //...
    MyClass operator* (float x);
};

前 2 个选项用作类范围之外的声明。

【讨论】:

  • 不是使用第一个参数隐式调用的重载运算符吗?那么如果第一个参数是基本数据类型(此处为浮点数),它会起作用吗?
  • @vaisakh 如果您至少提供用户定义的类型,则可以重载任何二元运算符。在这种情况下,MyClass 是用户定义的。所以你可以定义operator +(int, const MyClass&),但你不能重新定义operator +(int,int)
  • 它可以工作 - 运算符的范围仅限于声明它的对象。在第一种情况下,微妙之处在于函数不是 MyClass 的成员函数,它们处于全局范围内 - 即使第一个参数是浮点数,依赖于参数的查找也会找到它们。
  • @Snowman 你在课堂上声明了吗?如果是这样,那么this 是一个隐式参数,所以它仍然是一个二元运算符。前 2 个选项用作类范围之外的声明。
  • 一个小附录:如果定义在头文件中时发生链接器错误,请声明两个重载inline
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 2011-04-05
相关资源
最近更新 更多