加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何解决转换构造函数和普通构造函数之间的歧义?

发布时间:2020-12-16 07:11:58 所属栏目:百科 来源:网络整理
导读:我期待消除普通构造函数和自动转换构造函数之间的歧义. 据我所知,通过将普通构造函数声明为显式,可以部分消除这种歧义,因此编译器将避免使用此构造函数作为转换构造函数,如下所示: #include iostream#include fstreamclass Integer{ int i ;public: explici
我期待消除普通构造函数和自动转换构造函数之间的歧义.

据我所知,通过将普通构造函数声明为显式,可以部分消除这种歧义,因此编译器将避免使用此构造函数作为转换构造函数,如下所示:

#include <iostream>
#include <fstream>

class Integer{
  int i ;

public:

  explicit  Integer (const int _i) : i(_i) {} //Normal constructor
  Integer (const int& ii ) : i (ii) {}        // conversion constructor
  operator int() {return int (i) ;}         // Auto-conversion operator

  friend std::ostream & operator <<(std::ostream &os,const Integer io ) {
    std::cout << io.i  ;
    return os ;
}

};


int main() {

// Integer io (5); call of overloaded ‘Integer(int)’ is ambiguous error 
  Integer io2 = 20 ;          // conversion constructor
  std:: cout << io2 << "n" ;
  int i = io2 ;               // auto-conversion operator
  std:: cout << i << "n" ;
}

输出:

20
20

我的问题是:

1-是否有一种强制使用构造函数作为转换构造函数的标准方法,因为有一种强制使用的标准方法作为普通构造函数?

2-使用转换构造函数和自动转换运算符是一个好习惯,换句话说,如果正常的构造函数没有用转换构造函数重载,我可以确保不同的编译器将构造函数用作转换构造函数吗?

谢谢

解决方法

Is there a standard way to force using a constructor as conversion
constructor,since there is a standard way to force usage as normal
constructor?

是的,您省略了explicit关键字.

is it a good practice to use conversion constructor and autoconversion
operators,in another words can I ensure that different compilers will
use the constructor as conversion constructor in case if normal
contructor is not overloaded with conversion constructor ?

如果编译器符合标准,那么这里没有问题.隐式结构没有错.当你构造对象的文字数组等时,它们可以非常方便.也可以令人惊讶.用你的判断.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读