2011-08-04 107 views
3

据我所知,从std :: string类继承是一个贫穷的想法,但只是想添加自定义函数字符串类的虚拟分配,使用继承。 我想调用我的函数作为'添加',当我做str.add(str1,str2);它应该在字符串的开始处追加str1,在字符串的末尾追加str2。这个类(继承的字符串类)是另一个类的私有成员类(称为Parent)。当我尝试访问我的字符串类对象时,它指向父类。我怎样才能做到这一点?添加功能串类

感谢

+1

也许一个代码示例? - 无论如何,无效组合(std :: string&body,const std :: string&prefix,const std :: string&suffix);'。继承字符串不会增加任何值,因为您必须使用公共接口来执行。 – UncleBens

+0

'str1 + str + str2'? – GManNickG

回答

0

确保你在课堂的公开部分声明你的功能。

也许你会喜欢在继承组成;)

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; 
    } 
2

不要std::string继承,这确实是一个坏主意。您将不得不编写适当的构造函数,并且从不使用多态性,因为std::string没有虚拟析构函数。只需写一个免费的功能。

3

我不确定我是否理解您的问题的所有方面。当你说一个私人成员类,你的意思是私人成员变量?还是私下继承?我不明白“当我试图访问我的字符串类对象,它指向父类”。

你说的没错,从性病继承:: string的可能不是一个很好的主意。首先,让它成为派生字符串的一员,需要你深入了解底层实现;这可能会从分发变为分发,使代码变得不可移植。如果你使用std :: string提供的已定义的接口编写一个可移植的实现,那么你将无法利用任何真正的优化。除非你有一个很好的理由,否则你最好不要这样做。

二,命名为“加”可能不是最好的,因为它似乎并没有描述自己在做什么。 “环绕声”可能是一个更好的名字。

我觉得像这样的外部功能可能会更好,避免从字符串继承的整体思路:

void surround(std::string &orig, std::string const &pre, std::string const &post) { 
    orig = pre + orig + post; 
} 

,或者,如果你想要更高的性能,做这样的事情:

void surround(std::string &orig, std::string const &pre, std::string const &post) { 
    std::string str; 
    str.reserve(orig.size() + pre.size() + post.size()); 
    str.insert(str.end(), pre.begin(), pre.end()); 
    str.insert(str.end(), orig.begin(), orig.end()); 
    str.insert(str.end(), post.begin(), post.end()); 
    std::swap(str, orig); 
} 
+0

谢谢大家的快速回复。 – keeda

+0

为了获得更高的性能,您不需要创建字符串的第四个临时实例。你可以添加和附加ro' orig'。 – 2011-08-04 19:09:44

+0

你可以,但它需要更多的内存分配和副本。这会降低性能。 – graphicsMan