次のようなコードがたくさんあります。
otherString1 = myString1.replace("a", "b").replace("c", "d").replace("e", "f");
otherString2 = myString2.replace("a", "b").replace("c", "d").replace("e", "f");
otherString3 = myString3.replace("a", "b").replace("c", "d").replace("e", "f");
何度も繰り返したくありませんreplace
。そのようなコードをリファクタリングするための正しいアプローチは何ですか? 私はC++が初めてです...
私はできると思った:
#define REPLACE .replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = myString1#REPLACE;
しかし、これは機能しません。
明らかに、文字列クラスにモンキーパッチを適用して追加することはできませんmyReplace()
...
何をすべきか?また、置換コードをヘッダーまたはソース ファイルに配置する必要がありますか? それらstatic
のinline
、、ものはどうconst
ですか?ヘルパー クラス全体とヘルパー メソッドを作成する必要がありますか、それとも関数だけをどこかに作成する必要がありますか? 次のようなものはどうですか:
[helper.hpp]
static inline const myReplace(const StringClass s);
[helper.cpp]
static inline const myReplace(const StringClass s) {
return s.replace("a", "b").replace("c", "d").replace("e", "f");
}
[somefile.cpp]
include "helper.hpp"
otherString3 = myReplace(myString3);