文字列を効果的に取得するメソッドがあります。ただし、使用したい文字列のサブセットは非常に限られています。私はtypedefのstd::stringをクラスとして考えていて、関数を明示的に呼び出していました。しかし、それがうまくいくかどうかはわかりません。アイデア?
3 に答える
通常のルールが引き続き適用されます。クラスは継承されるように設計されておらず、そのデストラクタは仮想ではないため、std :: string基本クラスにアップキャストし、オブジェクトを破棄すると、派生クラスになります。デストラクタは呼び出されません。
これが決して起こらないことを保証できる場合は、先に進んでください。
std::string
それ以外の場合は、基本クラスではなく、クラスのメンバーにすることができます。または、プライベート継承を使用できます。このアプローチの問題は、クラスを文字列として使用できるようにするには、文字列インターフェイスを再実装する必要があることです。
getString()
または、クラスを定義して、内部std::string
オブジェクトを返す関数を公開することもできます。その後も独自のクラスを渡すことができ、を渡そうとするとコンパイラは文句を言いますstd::string
が、必要なときに内部文字列にアクセスできます。それが最善の妥協案かもしれません。
入力を制限したいようです(つまり、文字のみを許可する文字列)。
クラス内で文字列を使用してから、必要な関数をラップすることをお勧めします。
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;
}
制限された文字列を受け入れるメソッドが1つあるようです。新しいクラスは本当に必要ですか?
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 );