[英]C++ helper function
我有很多这样的代码:
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);
海事组织,你想得太多。 只需创建一个接受字符串(通过const
引用)并返回修改后的字符串的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);
我只想指出您的宏会起作用,只是您使用不正确。 但是,这不是解决此问题的正确方法 ,只是想指出一点。 这是正确的用法:
#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);
请记住, 不要这样做 ,但这是可以使用宏的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.