c++使用赋值操作符模拟类型转换
c++ emulate typecasting using assignment operator
这是我的类——
class stuff
{
private:
char s_val = 'x';
char e_val = 'y';
public:
stuff() {;}
stuff(const string &s) {
this->s_val = s[0];
this->e_val = s[s.length() - 1];
}
stuff(const stuff &other) {
this->s_val = other.s_val ;
this->e_val = other.e_val ;
}
stuff& operator=(const stuff &other)
{
this->s_val = other.s_val;
this->e_val = other.e_val;
return *this;
}
stuff& operator=(const string &s)
{
*this = stuff(s);
return *this ;
}
stuff& operator=(const char *c)
{
string s(c);
*this = stuff(s);
return *this ;
}
friend ostream& operator<<(ostream &os, const stuff &s)
{
os << s.s_val << " " << s.e_val ;
return os ;
}
};
这是我的主要——
stuff s1("abc");
cout << s1 << endl ;
stuff s2(s1);
cout << s2 << endl ;
stuff s3 = s2 ;
cout << s3 << endl ;
stuff s4; s4 = "def" ;
cout << s4 << endl ;
// stuff s5 = "def" ; // compiler does not like it
// cout << s5 << endl ;
所以当我说stuff s5 = "def"
时编译器认为我试图在string
和stuff
之间进行某种类型转换,它说——
error: conversion from ‘const char [4]’ to non-scalar type ‘stuff’ requested
但是我实际上想做的是通过说stuff s5 = "bcd"
来模仿语句stuff s5("bcd")
。
如何实现这样的编码结构?
这将无法编译,因为您的隐式构造函数接受const std::string&
而不是const char*
。const char*
可以转换为const std::string
,但编译器只会进行一次隐式转换,以尝试实现您的构造函数。您可以通过添加一个构造函数来解决这个问题,该构造函数接受const char*
并委托给字符串构造函数(需要c++ 11):
stuff(const char* s) : stuff {std::string{s}} {}
您需要一个以const char *
为参数的转换构造函数。在c++ 11或更高版本中,这可以委托给您现有的string
构造函数:
stuff(const char * s) : stuff(std::string(s)) {}
从历史上看,或者如果您想避免创建临时字符串,它可能是最简单的
stuff(const char * s) {
this->s_val = s[0];
this->e_val = s[std::strlen(s)-1];
}
(遵循构造函数体中的赋值约定,而不是直接初始化)
如果没有这个,将不允许从字符串文字进行隐式转换,因为它需要两个用户定义的转换(const char *
到std::string
再到stuff
),但是隐式转换序列只能包含一个。显式转换(如stuff s5("bcd");
)可以通过string
构造函数完成。
您还可以删除复制构造函数和复制赋值操作符:它们的作用与隐式生成的操作符完全相同。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何将Windows产品类型转换为名称?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 事件系统:使用类型转换或联合进行继承
- 通过隐式类型转换模拟接口
- c++使用赋值操作符模拟类型转换