我想扩展std :: string,但不是因为你可能会想 [英] I want to extend std::string, but not for the reason you might think
问题描述
我有一个方法,有效地接受一个字符串。然而,有一个非常有限的字符串子集我想使用。我在想象typedef'ing std :: string作为一些类,并调用显式的函数。我不知道这将工作,但是。想法?
I have a method that effectively takes a string. However, there is a very limited subset of strings I want to use. I was thinking of typedef'ing std::string as some class, and call the functions explicit. I'm not sure that would work, however. Ideas?
推荐答案
通常的规则仍然适用:该类不是设计为继承自,其析构函数不是虚拟的,所以如果你向上转换为std :: string基类,并让对象被销毁,你的派生类的析构函数不会被调用。
The usual rule still applies: the class isn't designed to be inherited from, and its destructor isn't virtual, so if you ever upcast to the std::string base class, and let the object be destroyed, your derived class' destructor won't be called.
如果你可以
否则,你可以使 std :: string
成为一个成员的类,而不是一个基类。或者你可以使用私有继承。这种方法的问题是你必须重新实现该类的字符串接口,使其可以用作字符串。
Otherwise, you could make the std::string
a member of your class, rather than a base class. or you could use private inheritance. The problem with this approach is that you'd have to re-implement the string interface for the class to be usable as a string.
或者你可以定义你的类暴露一个返回内部 std :: string
对象的 getString()
函数。然后你仍然可以传递你自己的类,如果你尝试传递一个 std :: string
,编译器会抱怨,但内部字符串可以访问,当你需要它。这可能是最好的妥协。
Or you could just define your class to expose a getString()
function which returns the internal std::string
object. Then you can still pass your own class around, and the compiler will complain if you try to pass a std::string
, but the internal string is accessible when you need it. That might be the best compromise.
这篇关于我想扩展std :: string,但不是因为你可能会想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!