【问题标题】:How to overload an operator == inside an other class如何在另一个类中重载运算符 ==
【发布时间】:2019-04-19 15:12:10
【问题描述】:

我有一个 A 类

在模板类 B 中

template<class key>
class B

我想在 B 类中重载 A 的 == 运算符,因为我不希望它在类外被重载

我该怎么做?

我试过了:

1.

bool operator==(const key &a, const key &b)

编译结果:参数太多

2.

friend operator==(const key &a, const key &b)

当我尝试使用操作符时,编译结果:找不到操作符

【问题讨论】:

  • 如何在私有命名空间中定义运算符,然后在 using 中定义 B 的成员函数定义?
  • @Quentin 想过这个解决方案,但我认为它不够优雅

标签: c++ templates overloading


【解决方案1】:

您可以为您的密钥类型定义一个嵌套的私有包装器:

template<class key>
class B
{
    struct EKey {
        key k;
        friend bool operator==(const EKey&, const EKey&) { return false; }
    };
    // ...
};

完整演示:http://coliru.stacked-crooked.com/a/2fd8e570f2b12a3e

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 2014-08-30
    • 2013-09-26
    • 2021-05-23
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多