我正在开发一个项目,我希望可以指定要使用几类方法/算法/函数中的哪一类。每个方法“类”都提供相似的功能,并且可以与其他类互换。
我试图用一个基本抽象类来实现这个,方法“类”作为派生类:
class Method {
public:
virtual int function1(int) = 0;
virtual int function2(int, int) = 0;
};
class Method1 : public Method {
public:
int function1(int a) {
return a * 2;
}
int function2(int a, int b) {
return a + b;
}
};
class Method2 : public Method {
public:
int function1(int a) {
return a / 2;
}
int function2(int a, int b) {
return a - b;
}
};
void useMethod(int a, int b, Method& m) {
int result1 = m.function1(a);
int result2 = m.function2(a, b);
/* Do something with the results here */
}
int main() {
// Doesn't work, "type name is not allowed"
useMethod(1, 2, Method1);
useMethod(1, 2, Method2);
// Works, but seems unnecessary and less elegant
Method1 x;
useMethod(1, 2, x);
Method2 y;
useMethod(1, 2, y);
return 0;
}
问题是我似乎无法弄清楚如何在不创建它们的实例的情况下允许使用 Method1
和 Method2
- 这在我看来是不必要的,因为它们都会提供相同的功能。 是否有某种方法可以使派生类成为某种“静态”类,以便在没有实例的情况下使用它们?
最佳答案
你可以这样做:
useMethod(1, 2, Method1());
useMethod(1, 2, Method2());
否则不,你不能有 static virtual
方法。不过,您可以使用模板实现类似的目的:
template<typename T>
void useMethod(int a, int b)
{
int result1 = T().function1(a); //or if you made the methods static then T::method1(a)
int result2 = T().function2(a, b); //ditto
/* Do something with the results here */
}
和用法:
useMethod<Method1>(1, 2);
然后你不需要基础抽象类,也不需要虚拟方法。如代码注释中所述,您可以将方法设为静态,这样就不需要类的实例了。
关于c++ - 可以像使用静态类函数那样使用派生类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414821/