c++中的显式运算符+

explicit operator + in C++

本文关键字:运算符 c++      更新时间:2023-10-16

我只是在玩+运算符&我不知道如何声明它并"显式地"使用它请帮助代码如下:

class compex{
    int real;
    int img;
public:
    compex();
    compex(int,int);
    compex& explicit operator + (const compex& P1)
    friend ostream& operator <<(ostream& out,const compex& R);
};

,操作符的实现为:

  compex& compex :: operator + (const compex& P1)
 {
    this->real += P1.real;
   this->img += P1.img;
   return *this;
 }

您不能将(这些)操作符设置为explicit(只有转换操作符可以在c++ 11中显式设置)。你不需要这么做。只需避免显式转换到您的类型,通过:

  • 没有定义其他类型的转换操作符,并且…
  • 标记所有可以用一个参数explicit调用的复合函数。

这样,您可以有效地只使用已经是complex的类型调用operator+

显式关键字仅对具有一个参数的构造函数有用。它将阻止编译器使用该构造函数进行转换。我不知道你让+运算符显式是想要达到什么目的。:)

如果您想要一个explicit转换函数,您将不得不为此目的编写一个(见这里)(但它只能使用一个参数)。

至于你的operator+(...),只要删除explicit,它应该工作。

Compex c1(1,2);
Compex c2(3,12);
Compex c3 = c1 + c2;

如果您希望在使用operator +时防止类型隐式转换为compex,您可以利用模板参数。

模板形参不直接服从类型转换规则。

class compex{
    template<class C, 
             typename std::enable_if<std::is_same<C,complex>::value>::type >  
    compex& operator + (const C& P1)
    {
       // Your code
    }
};