我扩展了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");
我不确定在哪里需要明确地进行类型转换。
如果复制构造函数不是显式的,代码可以正常工作,但我想知道并实现显式定义,而不是“猜测适当的转换”。
CustomString s = customStringObjectOnStack;
? - abumusamqc.append(static_cast<std::string>(*this))
可以用于隐式复制构造函数声明。所以一切都好。这个线程可以关闭了。 - abumusamqCustomString s( customStringObjectOnStack );
来实现CustomString s = customStringObjectOnStack;
,而不是隐式地使用=
语法来调用复制构造函数。 - David Rodríguez - dribeas