向字符串类添加函数
我知道从 std::string 类继承是一个糟糕的主意,但只是尝试使用继承向 string 类添加自定义函数以进行虚拟分配。 我想将我的函数称为“add”,当我执行 str.add(str1,str2); 时它应该在字符串的开头附加 str1,在字符串的末尾附加 str2。这个类(继承的字符串类)是另一个类(比如Parent)的私有成员类。当我尝试用它访问我的字符串类对象时,它指向父类。我该怎么做?
谢谢
I understand that inheriting from std::string class is a poor idea, but was just trying to add a custom function to string class for a dummy assignment, using inheritance.
I want to call my function as 'add' and when I do str.add(str1,str2); it should append str1 at the beginning of the string and str2 at the end of the string. This class(inherited string class) is a private member class of another class(say Parent). when I try to access my string class object with this, it points to the Parent class. How can I do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定我是否理解你问题的所有方面。当你说私有成员类时,你的意思是私有成员变量吗?还是私人继承?我不明白“当我尝试用它访问我的字符串类对象时,它指向父类”。
你是对的,从 std::string 继承可能不是一个好主意。首先,使其成为派生字符串的成员需要您对底层实现有相当多的了解;这可能会因发行版而异,从而导致代码不可移植。如果您确实使用 std::string 提供的已定义接口编写了可移植的实现,那么您将无法利用任何真正的优化。除非你有充分的理由这样做,否则你最好根本不这样做。
其次,“add”这个名字可能不是最好的,因为它似乎没有描述你正在做的事情。 “环绕”可能是一个更好的名字。
我认为像这样的外部函数可能会更好,避免从 string 继承的整个想法:
或者,如果您想要更高的性能,请执行以下操作:
I'm not sure I understand all aspects of your question. When you say a private member class, do you mean private member variable? Or is it privately inheriting? I don't understand "when I try to access my string class object with this, it points to the Parent class".
You're right, inheriting from std::string is probably not a very good idea. First of all, making it a member of a derived string requires that you know quite a lot about the underlying implementation; this may change from distribution to distribution making the code non-portable. If you do write an implementation that is portable, using the already-defined interface provided by std::string, you won't be able to take advantage of any real optimization anyway. Unless you have a really good reason for this, you're better off not doing it at all.
Second, the name "add" is probably not the best, as it doesn't seem to describe what you're doing. "surround" may be a better name.
I think an external function like this might be better, avoiding the whole idea of inheriting from string:
or, if you want higher performance, do something like this:
不要继承
std::string
,这确实是一个坏主意。您必须编写正确的构造函数,并且永远不要将其与多态性一起使用,因为std::string
没有虚拟析构函数。只需编写一个免费函数即可。Do not inherit from
std::string
, that is really a bad idea. You will have to write proper constructors, and never use it with polymorphism, becausestd::string
has no virtual destructor. Just write a free function.确保在类的公共部分声明您的函数。
也许你会喜欢组合而不是继承;)
Be sure you declare your function in public section of class.
Maybe you would love composition over inheritance ;)