我已经扩展了 std::string 以满足我必须将自定义函数构建到名为 CustomString 的字符串类中的需要
我已经定义了构造函数:
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");
我不确定在哪里明确需要强制转换。
如果复制构造函数不是显式的,则代码可以正常工作,但我想知道并实现显式定义而不是“猜测正确的强制转换”。
原文由 abumusamq 发布,翻译遵循 CC BY-SA 4.0 许可协议
显式复制构造函数意味着不会隐式调用复制构造函数,这就是表达式中发生的情况:
这个表达式的字面意思是:使用带有
CustomString
的构造函数创建一个临时的const char*
。隐式调用CustomString
的复制构造函数以从该临时复制到s
。现在,如果代码是正确的(即如果复制构造函数不是显式的),编译器将通过直接使用字符串文字构造
s
来避免创建临时文件并省略副本。但是编译器仍然必须检查构造是否可以完成并且在那里失败。您可以显式调用复制构造函数:
但我建议您完全避免临时使用,只需使用
s
const char*
:这就是编译器无论如何都会做的事情……