【问题标题】:C++ two-way operators, is it possible?C++ 双向运算符,有可能吗?
【发布时间】:2014-11-10 21:25:47
【问题描述】:

例如,我们有这个类:

class my_class
{
public:
  friend my_class operator* (const my_class&, int a);
  friend my_class operator* (int a, my_class&);  
};

my_class operator* (int a, my_class&)
{
    // do my_class * a
}

my_class operator* (int a, my_class&)
{
    // do a * my_class
}

是否可以只做一个 operator* 来做这两个做的事情?

谢谢!

【问题讨论】:

  • 第二个表单不应该返回my_class吗?
  • 第一个可以做my_class * a,但第一个只做my_class * my_class,如果它是一个成员函数或编译器错误,因为全局运算符函数需要两个参数。
  • 你真正想要的语义是什么?乘法、解引用?
  • @πάνταῥεῖ 倍增!我刚刚写了一个简短的问题,对于语义错误,抱歉!
  • @marquesm91 “我刚刚写了一个简短的问题,” 请记住,本网站旨在帮助未来的研究人员提出问题。您是否会认为您的问题对于其他没有看到您实际拥有的代码、意在使用的语义的人来说是这样的?请检查您要改进的问题。

标签: c++ operator-overloading overloading


【解决方案1】:

你不能那样做。但是,您可以实现一个并简单地从另一个调用它:

my_class operator *(const my_class &l, int r) {
    // implement the actual operator here.
}

my_class operator *(int l, const my_class &r) {
    return r * l;
}

(注意,后一个函数不能作为类的一部分实现,必须在外部实现。第一个函数可以作为实例方法实现,因为它的第一个参数是类类型。)

【讨论】:

  • 谢谢,这对我有很大帮助!
【解决方案2】:

你可以通过使用另一个来实现一个:

my_class operator*(int lhs, const my_class& rhs)
{
    return rhs * lhs;
}

如果操作本身是可交换的。情况并非总是如此,所以要小心。

还有一些库可以帮助您使用某些运算符。如果你有

my_class mc, a, b;
a = mc * 1;
b = 1 * mc;

您可能还希望能够做类似的事情

mc *= 1;

在这种情况下,您只需实现

my_class& my_class::operator*=( int v );

您可以使用Boost.Operatorsdf.operators 自动生成其他运算符。

例子:

struct my_class
    : df::commutative_multipliable< my_class, int >
{
    // ...

    my_class& operator*=( int v )
    {
        // ... implement me!
        return this;
    }

    // ...
};

在此示例中,您再次只实现 一个 操作,其余操作使用通用模式生成。

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2013-09-19
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多