我很快为这个问题写了下面的类。
我正在寻找一种方法将 addFruit()
与 removeFruit()
合并以减少代码。
它们都使用相同的条件,但最后的函数调用不同。
我的代码:
#include <iostream>
#include <string>
#include <vector>
class MyClass
{
public:
void addFruit(const std::string &str, int count)
{
if (str == "apples")
addToVec(apples, count);
else if (str == "oranges")
addToVec(oranges, count);
else if (str == "lemons")
addToVec(lemons, count);
else if (str == "melons")
addToVec(melons, count);
else if (str == "bananas")
addToVec(bananas, count);
else
std::cout << "Unknown Fruit : " << str << '\n';
}
void removeFruit(const std::string &str)
{
if (str == "apples")
removeFromVec(apples);
else if (str == "oranges")
removeFromVec(oranges);
else if (str == "lemons")
removeFromVec(lemons);
else if (str == "melons")
removeFromVec(melons);
else if (str == "bananas")
removeFromVec(bananas);
else
std::cout << "Unknown Fruit : " << str << '\n';
}
private:
void addToVec(std::vector<int> &vec, int count)
{
vec.push_back(count);
}
void removeFromVec(std::vector<int> &vec)
{
vec.pop_back();
}
std::vector<int> apples;
std::vector<int> oranges;
std::vector<int> lemons;
std::vector<int> melons;
std::vector<int> bananas;
};
有什么聪明的方法可以很好地合并这两个函数,从而减少代码量?
最佳答案
做一个额外的功能,例如determineTargetVector(const std::string &str)
返回相应的 vector ,您要在其中插入/删除元素,因此没有多余的条件。此外,每个功能只有一个责任也很好。
例如:
std::vector<int> *determineTargetVector(const std::string &str)
{
if (str == "apples")
return &apples;
else if (str == "oranges")
return &oranges;
else if (str == "lemons")
.
.
.
else
//something invalid, to check for in superior function
return nullptr;
}
关于c++ - 如何合并具有相同条件的两个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52113009/