简体   繁体   English

定义显式重载构造函数问题

[英]defining explicit overloaded constructor issue

I have following class that some of the operators are overloaded: 我有以下课程,某些运算符已重载:

class CLASS1
{
       CLASS1();
       CLASS1(const CLASS1 &obj);

   CLASS1 operator +(const CLASS1 &obj) {
       CLASS1 srcObj;
       // doing add stuff here
           return srcObj;
       }

   void func()
   {
   CLASS1 boj = // some method which returns CLASS1 obj.
   }


   CLASS1& operator =(const CLASS1 &obj) {
       // copy properties
       }
}

Ok, this works fine. 好的,这很好。 but after awhile I decided to make my class explicit to avoid implicit conversions. 但是过了一会儿,我决定让我的班级显式以避免隐式转换。 Therefore, I've made it this way: 因此,我这样做是这样的:

class CLASS1
{
       explicit CLASS1();
       explicit CLASS1(const CLASS1 &obj);

   CLASS1 operator +(const CLASS1 &obj) {
       CLASS1 srcObj;
       // doing add stuff here
           return srcObj;          // compiler gives non-matching errors
   }

   void func() {
       CLASS1 boj = somemethods(); // compiler gives non-matching errors
   }

   CLASS1& operator =(const CLASS1 &obj) {
       // copy properties
       }
}

Now, the compiler gives 'no matching function to call...' error (specified in the code above), in spite of I've explicitly overloaded assignment operator. 现在,尽管我显式重载了赋值运算符,但编译器给出了“没有匹配的函数来调用...”错误(在上面的代码中指定)。 Where is my mistake? 我的错误在哪里?

When you return an object by value the copy-constructor is called implicitly . 当按值返回对象时,将隐式调用copy-constructor。 If you say it's not allowed to be called implicitly you will get an error. 如果您说不允许隐式调用它,则会出现错误。

You should not use explicit for your default, copy or move constructors. 您不应该对explicit ,复制或移动构造函数使用explicit Or for constructors taking more than one argument. 或对于采用多个参数的构造函数。 Only for constructors taking a single argument (with the noted exceptions). 仅适用于采用单个参数的构造函数(带有注明的异常)。

Technically speaking, when returning an object from a method, an object you receive outside method call is actually a copy of an object you declare inside method. 从技术上讲,从方法返回对象时,在方法调用外部收到的对象实际上是在方法内部声明的对象的副本。 So compiler must have a permitted way to "transfer contents" from in-method object to method result. 因此,编译器必须具有一种允许的方法,以将方法内对象中的“内容”转移到方法结果中。 Since in-method instance is no longer needed, the move is the best approach (yes, you need to add move constructor): 由于不再需要方法中的实例,因此移动是最好的方法(是的,您需要添加move构造函数):

CLASS1(CLASS1&& obj);

This will allow you to forbid implicit conversions, while maintaining the ability to have temporary objects. 这将允许您禁止隐式转换,同时保持拥有临时对象的能力。

In real life, the afforementioned copy/move will likely be optimized away by RVO/NRVO. 在现实生活中,上述复制/移动很可能会通过RVO / NRVO进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM