c++ - 创建作为运算符(operator)工作的方法

标签 c++

在 C++ 中是否可以创建用作重载运算符的自定义方法?例如简单的类:

class A
{
public:
  A(int val){ x = val;}
  int getInt(){ return (x + 2); }

private:
  int x;
};

如何执行方法toSpecialString,例如,该方法将以特殊方式格式化我返回的int,然后返回此字符串(例如“abc14”)。示例:

A a(12);
std::cout << a.getInt().toSpecialString() << std::endl;

作为输出,我期待“abc14”。 C++ 中可能有类似的事情吗?

最佳答案

当然,例如

class A
{

  struct ReturnedInt {
    int x;

    // constructor
    ReturnedInt(int x_) : x(x_) { }

    // "transparent" type cast to int
    operator int() { return x; }

    std::string toSpecialString() {
      std::ostringstream oss{};
      oss << "abc" << x;
      return oss.str();
    }
  };

public:
  A(int val){ x = val;}
  ReturnedInt getInt(){ return (x + 2); } // I changed the return type but see the remarks below

private:
  int x;
};

然后

int main () {
  A a{12};
  std::cout << a.getInt() << '\n';
  std::cout << a.getInt().toSpecialString() << '\n';
}

打印

14
abc14

前者被传递到 coutoperator<<作为一个普通的int (自动衰减)但在后者中我们使用返回值实际上是一个对象的事实。出于与前一行相同的原因,任何期望 int 的函数还将接受ReturnedInt 。此外,在编译后的二进制文件中,这种“包装器”结构的额外成本应该为零。

请注意,如果您不打算将内部类公开用于任何其他目的,则内部类可以是私有(private)的(如我的示例中所示)。这与它用作返回类型或其(公共(public))方法被调用的事实并不冲突。

关于c++ - 创建作为运算符(operator)工作的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48652544/

相关文章:

c++ - 构造函数和复制构造函数的顺序

c++ - "new"operator in multiple threads cause Segmentation Fault

c++ - 如果 block 无法访问错误

c++ - 带有证书验证的 native C++ HTTPS REST 调用

c++ - 使用 Boost 图库的 adjacency_matrix

c++ - C++ 中的崩溃恢复

c++ - 在字符串的VECTOR中记录特定子串出现的次数

c++ - 引用计数的发布-消费排序

c++ - 在 OpenCV/C++ 中通过(扩展)卡尔曼滤波器实现数据融合

c++ - 在一个大项目中找到被零除