C++ 靜態成員函數(Static Member Function)是一種特殊的成員函數,它不依賴于任何對象實例即可調用。靜態成員函數在以下應用場景中非常有用:
class MathUtils {
public:
static double square(double x) {
return x * x;
}
};
class Rectangle {
public:
static double area(double width, double height) {
return width * height;
}
};
class MyClass {
public:
static std::unique_ptr<MyClass> createInstance() {
return std::make_unique<MyClass>();
}
};
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
enum class Color {
Red,
Green,
Blue
};
Color getNextColor(Color color) {
return static_cast<Color>((static_cast<int>(color) + 1) % 3);
}
總之,靜態成員函數在 C++ 中具有廣泛的應用場景,它們提供了一種與類相關但不需要實例化的方法。