简体   繁体   English

C ++辅助函数

[英]C++ helper function

I have lots of code like this: 我有很多这样的代码:

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

I would like to not repeat those replace methods again and again. 我不想一次又一次重复那些replace方法。 What is the right approach to re-factoring of such code? 重构此类代码的正确方法是什么? I'm new to C++... 我是C ++的新手...

I thought I could do: 我以为我可以:

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

but this does not work. 但这不起作用。

I obviously cannot monkey-patch the string class to add myReplace() ... 我显然无法猴子修补字符串类以添加myReplace() ...

What to do? 该怎么办? And should I put the replacement code into header or the sourse file? 我应该将替换代码放入标头或源文件中吗? What about those static , inline , const things? 那那些staticinlineconst东西呢? Should I create a whole helper class and a helper method or should I create just a function somewhere? 我应该创建整个助手类和一个助手方法,还是只在某个地方创建一个函数? What about something like: 怎么样呢?

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

IMO, you are overthinking it. 海事组织,你想得太多。 Just create a function that takes a string (by const reference) and returns the modified string. 只需创建一个接受字符串(通过const引用)并返回修改后的字符串的const Declare it in a header and define in the corresponding .cpp file. 在标头中声明它,并在相应的.cpp文件中定义。

Job done. 任务完成。

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

I just want to point out that your macro would have worked, you just used it incorrectly. 我只想指出您的宏会起作用,只是您使用不正确。 However, this is not the right way to solve this problem , just wanted to point it out. 但是,这不是解决此问题的正确方法 ,只是想指出一点。 Here's the correct usage: 这是正确的用法:

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

Or maybe better (if using macros can ever be better): 也许更好(如果使用宏可以更好):

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

Remember, don't do this , but this is how macros could be used. 请记住, 不要这样做 ,但这是可以使用宏的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM