在c ++中向std :: string添加函数

问题描述 投票:-1回答:1

我只是想念c ++标准库字符串类中的一些函数,所以我只想自己添加这些函数。我写的是:

#include <string>


class String : public std::string
{
public:
    // some new fancy functions
};

并且后来通过阅读一些论坛注意到,从std :: string和标准库中的任何其他容器继承是一个坏主意。

我只需要普通的字符串,但是我自己编写了其他功能,如何才能以正确的方式实现呢?还是没有办法正确执行,而我必须正确设置自己的字符串类?

c++ string class inheritance c++-standard-library
1个回答
0
投票

首先-std::string有点混乱,按原样拥有太多方法。将功能集成到不需要在该类中的类中,并且可以使用更简单,更基础的类方法轻松地实现为独立功能,这是不好的设计。

而且-std :: string同时难以操作(它不是字符串缓冲区,也不是不可能操作,即不可变。

无论如何,实现独立功能的“正确方法”是独立的功能。例如,假设您要随机排列std::string的内容。好吧,要么:

std::string& jumble(std::string& str)

std::string jumble(std::string str)

取决于您是否想将字符串更多地用作不可变或可变的实体。

还请记住,我们实际上并没有一个单独的std::string类-我们有一个基于字符类型的模板(以及分配器等),因此,如果要通用,就必须接受此类:

template<
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> class basic_string;

-1
投票

我建议创建自己的类,并在该类上附加一个字符串变量,并且该类中包含的方法可以执行所需的其他功能。我认为这称为合成,但我不确定该术语。

示例:

class myString
{
private:
   std::myString x;
public:
   myString(std::string x);
   std::string getString();
   void setString(std::string x);

   // Add whatever functions you need to operate on the string "x"
};
© www.soinside.com 2019 - 2024. All rights reserved.