1

次のようなコードがたくさんあります。

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()...

何をすべきか?また、置換コードをヘッダーまたはソース ファイルに配置する必要がありますか? それらstaticinline、、ものはどう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);
4

2 に答える 2

5

IMO、あなたはそれを考えすぎています。const文字列を (参照によって) 受け取り、変更された文字列を返す関数を作成するだけです。ヘッダーで宣言し、対応する.cppファイルで定義します。

ジョブ完了。

[helper.hpp]
std::string myReplace(const std::string& s);

[helper.cpp]
std::string myReplace(const std::string& s) {
   ...
}

[somefile.cpp]
#include "helper.hpp"
otherString3 = myReplace(myString3);
于 2013-03-23T15:15:26.073 に答える
1

あなたのマクロは機能していたはずであり、使い方が間違っているだけです。ただし、これはこの問題を解決する正しい方法ではありません。指摘したかっただけです。正しい使い方は次のとおりです。

#define REPLACE .replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = myString1 REPLACE;

または、より良いかもしれません (マクロを使用する方が良い場合):

#define REPLACE(str) str.replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = REPLACE(myString1);

覚えておいてください、これをしないでください。しかし、これがマクロの使用方法です。

于 2013-03-23T15:24:06.207 に答える