C++ 不可见转换
我有一个具有构造函数和重载运算符的类:C++ 不可见转换,c++,C++,我有一个具有构造函数和重载运算符的类: MyInt(std::string); friend MyInt operator + (const MyInt &a, const MyInt &b); friend std::ostream& operator<<(std::ostream& out, const MyInt &value); 如何在不重载const char*的类构造函数或运算符的情况下修复它?隐式转换序列只能有一个用户定义的转换
MyInt(std::string);
friend MyInt operator + (const MyInt &a, const MyInt &b);
friend std::ostream& operator<<(std::ostream& out, const MyInt &value);
如何在不重载const char*的类构造函数或运算符的情况下修复它?隐式转换序列只能有一个用户定义的转换,调用std::string构造函数和MyInt构造函数都是用户定义的转换 因此,您需要提供这两种转换中的任何一种作为显式转换:
std::cout << my_int + std::string("123");
或
唯一的替代方法是为MyInt定义一个直接接受const char*或const char[N]的构造函数。问题是需要两个不允许的用户定义转换。第一个将字符串文本转换为std::string类型的对象。第二个将std::string类型的临时对象转换为MyInt类型的对象 您可以再引入一个构造函数,如
MyInt( const char * );
在这种情况下,运算符+将对表达式有效
否则你也得写
std::cout << my_int + MyInt( "123" );
或
消除一个用户定义的隐式转换。以字符串文字作为输入调用operator+,需要进行两次隐式转换,一次从const char[N]到temp std::string,然后从该std::string到MyInt。在隐式转换序列期间,编译器只允许执行1次转换
您应该将MyInt构造函数更改为按常量引用而不是按值获取std::string,这将允许编译器按原样使用temp std::string,而不必复制它:
MyIntconst std::string&
但这并不能解决错误。您需要消除其中一个转换。添加另一个接受常量字符[]或常量字符*作为输入的构造函数,例如:
样板
MyIntconst字符和[N]
MyIntconst字符*
您想添加模板MyTimeStCar和ARR[n]构造函数吗?我需要从CHAR-> STD::String > MyTetry+ +到抱歉,C++不这样工作。C++允许最大限度地进行一个隐式转换。@ KamilCuk提出的解决方案可以完成这项工作。
std::cout << my_int + MyInt("123");
MyInt( const char * );
std::cout << my_int + MyInt( "123" );
std::cout << my_int + std::string( "123" );