在没有类实例的情况下调用c ++类方法?

use*_*925 30 c++

是否可以在c++不首先创建类实例的情况下调用类方法?

假设我们有以下代码:

// just an example 
#include <iostream>
using namespace std;

class MyClass {
    public:
        MyClass();
        ~MyClass();
        int MyMethod(int *a, int *b);
};

// just a dummy method
int MyClass::MyMethod(int *a, int *b){;
    return a[0] - b[0];
}
Run Code Online (Sandbox Code Playgroud)

这是另一个例子:

#include <iostream>
using namespace std;

class MyClassAnother {
    public:
        MyClassAnother();
        ~MyClassAnother();
        int MyMethod(int *a, int *b);
};

// just a dummy method
int MyClassAnother::MyMethod(int *a, int *b){;
    return a[0] + b[0];
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到,在上面的例子中,两个类都没有内部变量,并使用虚拟构造函数/析构函数; 他们唯一的目的是揭露一种公共方法,MyMethod(..).这是我的问题:假设文件中有100个这样的类(所有类具有不同的类名,但具有相同的结构 - 一个具有相同原型的公共方法 - MyMethod(..).

有没有办法调用MyMethod(..)每个类的方法调用而不先为每个类创建一个类实例?

Gre*_*son 46

使用关键字"static"来声明方法:

static int MyMethod( int * a, int * b );
Run Code Online (Sandbox Code Playgroud)

然后你可以在没有像这样的实例的情况下调用方法:

int one = 1;
int two = 2;

MyClass::MyMethod( &two, &one );
Run Code Online (Sandbox Code Playgroud)

'static'方法是仅将类用作命名空间的函数,不需要实例.


Mar*_*som 5

您可以通过声明来调用没有实例的类方法static,但这似乎不是您想要的。您希望能够在 100 个不同的类上调用相同的方法。

C++ 有两种方法来区分不同的类方法。一种是在编译时进行,一种是在运行时进行。在编译时,您需要调用类名本身作为静态方法调用的一部分,或者您需要对象实例或指向特定派生类的指针。如果您已将方法声明为虚拟方法,则在运行时您可以多态地调用该方法。请注意,您需要该类的一个对象才能使用任一运行时方法。