首页 > 解决方案 > C++中的静态函数

问题描述

我在学习 C++ 时提出了一个问题。这是关于静态功能的。在这个头文件中,我创建了一个静态函数。

using namespace std;
class Date
{
public:
    int dd, mm, yy;
public:
    //Date();
    Date(int d, int m, int y);
    static bool LeapYear(Date t);
};

在这个源文件中,我定义了函数

{
    if ((t.yy % 400 == 0) || (t.yy % 4 == 0) && (t.yy % 100 != 0))
        return true;
    else
        return false;
}

据说静态函数无法访问非静态成员。但是当我将一个对象放入该函数时,它仍然可以工作。谁能为我解释一下?谢谢!

标签: c++

解决方案


静态和非静态成员函数之间的区别在于,当您调用非静态成员函数时,指向类实例的指针会作为第一个参数(this指针)隐式传递。您需要一个类(对象)的实例来调用非静态成员函数。因此,成员函数被授予访问类实例成员的权限。

相反,静态成员和静态成员函数不属于类实例,它们只是类定义的一部分。这就是为什么他们不能访问任何非静态类成员。这也是静态函数不能标记为 const 的原因,因为没有实例可以修改。

class Date
{
public:
    int dd, mm, yy;

public:
    Date(int d, int m, int y);

    // static function
    // can't be marked const because it makes no sense
    static bool LeapYear(Date t) /*const*/ {
        if ((t.yy % 400 == 0) || (t.yy % 4 == 0) && (t.yy % 100 != 0))
        return true;
    else
        return false;  
    }
    
    // member function - has access to this and thus to any non-static member of the instance
    // marked const because it doesn't change the instance
    bool isLeap() const {
        if ((/*this->*/yy % 400 == 0) || (yy % 4 == 0) && (yy % 100 != 0))
        return true;
    else
        return false;  
    }
};

推荐阅读