向字符串类添加函数 [英] Adding function to string class

查看:138
本文介绍了向字符串类添加函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从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?

感谢

推荐答案

也许你会喜欢组合而不是继承)

Maybe you would love composition over inheritance ;)

    class MyString
    {
           std::string m_string; // do not inherit just composition it
    public:
            explicit MyString(const std::string& str)
                   : m_string(str)
            {
            }

            // your function should be in public scope I think
            MyString& add(const std::string& begin, const std::string& end)
            {
                    m_string.insert(0, begin);
                    m_string.append(end);
                    return *this;
            }

            const std::string& string() const
            {
                    return m_string;
            }
    };

    class Parent
    {
            MyString m_string;
    public:
            void surround(const std::string& begin, const std::string& end)
            {
                    m_string.add(begin, end);
            }
    };

    int main(int argc, char *argv[])
    {
            std::cout << MyString("inherit").add("Do not ", " from std::string!").string() << std::endl;
            return 0;
    }

这篇关于向字符串类添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆