gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:16:49 24 4
gpt4 key购买 nike

我期待消除普通构造函数和自动转换构造函数之间的歧义。

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

#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 ?

如果编译器符合标准,那么这里就没有问题。隐式结构没有错。当您构建对象等的文字数组时,它们会非常方便。也能出人意料。使用您的判断。

关于c++ - 如何解决转换构造函数和普通构造函数之间的歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29945771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com