c++ - 可以像使用静态类函数那样使用派生类吗?

标签 c++ oop

我正在开发一个项目,我希望可以指定要使用几类方法/算法/函数中的哪一类。每个方法“类”都提供相似的功能,并且可以与其他类互换。

我试图用一个基本抽象类来实现这个,方法“类”作为派生类:

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;
}

问题是我似乎无法弄清楚如何在不创建它们的实例的情况下允许使用 Method1Method2 - 这在我看来是不必要的,因为它们都会提供相同的功能。 是否有某种方法可以使派生类成为某种“静态”类,以便在没有实例的情况下使用它们?

最佳答案

你可以这样做:

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/

相关文章:

c++ - 如何在预处理器中检测 "Use MFC"

c++ - C++ 中的 (...) 参数是做什么的

php - fatal error : Uncaught Error: Call to a member function select() on null

javascript - 绑定(bind)点击失去了我的类(class)的上下文。 JS

c++ - Qt:按下按钮时显示多个窗口

c++ - 当涉及数组时,我们可以安全地从 C++ 调用 C API 函数吗?

javascript - JS OOP 从构造函数调用方法

php - OOP (PHP) - 强制重写方法根据父方法调用

python - 如何将某些内容添加到属性中?

c++ - basic_istream::seekg() 似乎不起作用