扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c++静态成员函数如何调用

扬州沐宇科技
2024-04-16 10:18:08
c++

静态成员函数可以直接通过类名或者对象名来调用。以下是两种方式:

  1. 通过类名调用静态成员函数:
class MyClass {
public:
    static void staticFunction() {
        // 静态成员函数的实现
    }
};

int main() {
    MyClass::staticFunction(); // 通过类名调用静态成员函数
    return 0;
}
  1. 通过对象名调用静态成员函数(不推荐):
class MyClass {
public:
    static void staticFunction() {
        // 静态成员函数的实现
    }
};

int main() {
    MyClass obj;
    obj.staticFunction(); // 通过对象名调用静态成员函数,不推荐这种方式
    return 0;
}

虽然通过对象名调用静态成员函数也是合法的,但不推荐这种方式,因为静态成员函数与类本身相关,而不是与对象相关。因此最好还是通过类名调用静态成员函数。

扫码添加客服微信