C ++帮助函数

时间:2013-03-23 15:12:45

标签: c++

我有很多像这样的代码:

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

怎么办?我应该将替换代码放入标题或sourse文件中吗?那些staticinlineconst件事情呢?我应该创建一个完整的帮助器类和一个帮助器方法,还是应该在某个地方创建一个函数?怎么样:

[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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

请记住,不要这样做,但这就是宏的使用方式。