3

我有一个有效地接受字符串的方法。但是,我想使用的字符串子集非常有限。我正在考虑 typedef'ing std::string 作为某个类,并显式调用这些函数。但是,我不确定这是否可行。想法?

4

3 回答 3

8

通常的规则仍然适用:该类并非旨在继承,其析构函数也不是虚拟的,因此如果您向上转换为 std::string 基类,并让对象被销毁,您的派生类'不会调用析构函数。

如果你能保证这永远不会发生,那就继续吧。

否则,您可以将其std::string设为类的成员,而不是基类。或者你可以使用私有继承。这种方法的问题是您必须重新实现字符串接口才能使该类可用作字符串。

或者你可以定义你的类来公开一个getString()返回内部std::string对象的函数。然后你仍然可以传递你自己的类,如果你试图传递 a std::string,编译器会抱怨,但是当你需要它时,内部字符串是可以访问的。这可能是最好的妥协。

于 2010-03-18T20:27:45.270 回答
7

听起来您想限制输入(即,可能是一个只允许字母的字符串)。

我建议在一个类中使用一个字符串,然后包装你想要的函数。

class limited_string
{
    std::string str;

public:
    limited_string(const char *data)
        : str(data)
    {
        if (!valid(str))
            throw std::runtime_exception(); 
    }

    virtual ~limited_string() {}

    limited_string &operator+=(const char *data)
    {
        // do all your work on the side - this way you don't have to rollback
        // if the newly created string is invalid
        std::string newstr(str);
        newstr += data;
        if (!valid(newstr))
            throw std::runtime_exception();

        str = newstr;
    }

    virtual bool valid(const std::string str) = 0;
}
于 2010-03-18T20:27:16.287 回答
0

听起来您有一种方法可以接受受限制的字符串。真的有必要上新课吗?

void needs_restricted_string( std::string const &str ) {
    if ( ! is_restricted_string( str ) ) throw std::runtime_error( "bad str" );
    …
}

否则,您唯一要捕获的是字符串是否满足限制。is_restricted_string()我看到的和编译时类之间的唯一区别是性能,如果你有一个专门用于检查字符串的存储结构。不要过早优化。也就是说,将太多功能放入新类或像字符串一样使用它也是错误的。

class restricted_string {
    std::string storage;
public:
     // constructor may implement move or swap() semantics for performance
     // it throws if string is no good
     // not explicit, may be called for implicit conversion
    restricted_string( std::string const & ) throw runtime_error;
     // getter should perhaps be private with needs_restricted as friend
    std::string const &str() const { return storage; }
}; // and no more functionality than that!

void needs_restricted_string( restricted_string const &str ) {
    std::string const &known_restricted = str.str();
}

std::string mystr( "hello" );
needs_restricted_string( mystr );
于 2010-03-18T21:36:49.653 回答