我扩展了 std::string 以满足我的需要,必须将自定义函数构建到名为的字符串类中自定义字符串
我已经定义了构造函数:
class CustomString : public std::string {
public:
explicit CustomString(void);
explicit CustomString(const std::string& str);
explicit CustomString(const CustomString& customString);
//assignment operator
CustomString& operator=(const CustomString& customString);
... };
在第三个构造函数(复制构造函数)和赋值运算符中,其定义为:
CustomString::CustomString(const CustomString& customString):
std::string(static_cast<std::string>(customString))
{}
CustomString& CustomString::operator=(const CustomString& customString){
this->assign(static_cast<std::string>(customString));
return *this;
}
首先,因为这是“明确的”;意味着需要显式转换才能分配给另一个 CustomString 对象;它抱怨任务。
CustomString s = CustomString("test");
我不确定到底在哪里明确需要铸造。
如果复制构造函数不显式,代码可以正常工作,但我想知道并实现显式定义,而不是“猜测正确的转换”。
显式复制构造函数意味着复制构造函数不会被隐式调用,这就是表达式中发生的情况:
CustomString s = CustomString("test");
这个表达的字面意思是:创建一个临时的CustomString
使用带有 a 的构造函数const char*
。隐式调用复制构造函数CustomString
从临时复制到s
.
现在,如果代码正确(即,如果复制构造函数不显式),编译器将避免创建临时对象并通过构造来删除复制s
直接使用字符串文字。但编译器仍然必须检查构造是否可以完成并在此处失败。
您可以显式调用复制构造函数:
CustomString s( CustomString("test") );
但我建议你完全避免临时的,只创建s
与const char*
:
CustomString s( "test" );
无论如何,这就是编译器会做的事情......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)